java打开指定路径的文件|java根据路径读取文件

|

1. java中用相对路径打开文件。

1、在Java开发工具的project中使用相对路径

在project中,相对路径的根目录是project的根文件夹,在此就是repathtest文件夹了。创建文件的写法是:

Filef=newFile("src/com/lavasoft/res/a.txt");Filef=newFile("doc/b.txt");

注意:路径不以“/”开头;

脱离了IDE环境,这个写法就是错误的,也并非每个IDE都如此。

2、通过CLASSPATH读取包内文件

读取包内文件,使用的路径一定是相对的classpath路径,比如a,位于包内,此时可以创建读取a的字节流:

InputStreamin=ReadFile.class.getResourceAsStream("/com/lavasoft/res/a.txt");

有了字节流,就能读取到文件内容了。

注意:这里必须以“/”开头;

3、看看完整的java中用相对路径打开文件测试代码:

packagecom.lavasoft.test;importjava.io.*;/***Java读取相对路径的文件**/publicclassReadFile{publicstaticvoidmain(String[]args){readTextA_ByClassPath();readTextA_ByProjectRelativePath();readTextB_ByProjectRelativePath();}/***通过工程相对路径读取(包内)文件,注意不以“/”开头*/publicstaticvoidreadTextA_ByProjectRelativePath(){System.out.println("—————–readTextA_ByProjectRelativePath———————");Filef=newFile("src/com/lavasoft/res/a.txt");Stringa=file2String(f,"GBK");System.out.println(a);}/***通过工程相对路径读取(包外)文件,注意不以“/”开头*/publicstaticvoidreadTextB_ByProjectRelativePath(){System.out.println("—————–readTextB_ByProjectRelativePath———————");Filef=newFile("doc/b.txt");Stringb=file2String(f,"GBK");System.out.println(b);}/***通过CLASSPATH读取包内文件,注意以“/”开头*/publicstaticvoidreadTextA_ByClassPath(){System.out.println("—————–readTextA_ByClassPath———————");InputStreamin=ReadFile.class.getResourceAsStream("/com/lavasoft/res/a.txt");Stringa=stream2String(in,"GBK");System.out.println(a);}/***文件转换为字符串**@paramf文件*@paramcharset文件的字符集*@return文件内容*/publicstaticStringfile2String(Filef,Stringcharset){Stringresult=null;try{result=stream2String(newFileInputStream(f),charset);}catch(FileNotFoundExceptione){e.printStackTrace();}returnresult;}/***文件转换为字符串**@paramin字节流*@paramcharset文件的字符集*@return文件内容*/(InputStreamin,Stringcharset){StringBuffersb=newStringBuffer();try{Readerr=newInputStreamReader(in,charset);intlength=0;for(char[]c=newchar[1024];(length=r.read(c))!=-1;){sb.append(c,0,length);}r.close();}catch(UnsupportedEncodingExceptione){e.printStackTrace();}catch(FileNotFoundExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}returnsb.toString();}}

2. 请问高手,java web开发]如何读取其他位置的指定文件

把A.txt文件包装成File,然后调用File里的Stringpath=file.getAbsolutePath();就可以完成你需要的东西了。Stringpaths="";//此处填写A.txt的父路径。Filefile=newFile(paths);Stringpath=file.getAbsolutePath();//paths的路径如果想自动得到,可以自己写一个方法去找A.txt文件,并记录它的路径即可。

3. java程序读取资源文件时路径如何指定

(1)、request.getRealPath("/");//不推荐使用获取工程的根路径 (2)、request.getRealPath(request.getRequestURI());//获取jsp的路径,这个方法比较好用,可以直接在servlet和jsp中使用 (3)、request.getSession().getServletContext().getRealPath("/");//获取工程的根路径,这个方法比较好用,可以直接在servlet和jsp中使用 (4)、 this.getClass().getClassLoader().getResource("").getPath();//获取工程classes 下的路径,这个方法可以在任意jsp,servlet,java文件中使用,因为不管是jsp,servlet其实都是java程序,都是一个 class。所以它应该是一个通用的方法。0、关于绝对路径和相对路径1.基本概念的理解绝对路径:绝对路径就是你的主页上的文件或目录在硬盘上真正的路径,(URL和物理路径)例 如:C:xyz est.txt 代表了test.txt文件的绝对路径。http://www.sun.com/index.htm也代表了一个URL绝对路径。相对路径:相对与某个基 准目录的路径。包含Web的相对路径(HTML中的相对目录),例如:在Servlet中,"/"代表Web应用的跟目录。和物理路径的相对表示。例 如:"./" 代表当前目录,"../"代表上级目录。这种类似的表示,也是属于相对路径。另外关于URI,URL,URN等内容,请参考RFC相关文档标准。RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax,(http://www.ietf.org/rfc/rfc2396.txt)2.关于JSP/Servlet中的相对路径和绝对路径。 2.1服务器端的地址服务器端的相对地址指的是相对于你的web应用的地址,这个地址是在服务器端解析的(不同于html和javascript中的相对 地址,他们是由客户端浏览器解析的)1、request.getRealPath方法:request.getRealPath("/") 得到的路径:C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\strutsTest\方法:request.getRealPath(".") 得到的路径:C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\strutsTest\.方法:request.getRealPath("") 得到的路径:C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\strutsTestrequest.getRealPath("web.xml") C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\strutsTest\web.xml2、request.getParameter("");ActionForm.getMyFile();方法:String filepath = request.getParameter("myFile"); 得到的路径:D:\VSS安装目录\users.txt方法:String filepath = ActionForm.getMyFile(); 得到的路径:D:\VSS安装目录\users.txt————————————————– strutsTest 为工程名myFile 在ActionForm中,为private String myFile; 在jsp页面中:为<html:file property="myFile"></html:file>

4. java根据路径读取文件

直接贴代码吧。不过这里要做一个简单的说明,对于这个程序,我们必须保证我们在C盘下有一个Users\HP\Desktop的文件夹,因为在后面写入文件的时候,如果路径中的文件不存在,是程序可以自动为其添加,但如果没有了这个路径,则程序会报找不到文件路径的异常。你可以对这个异常进行人性的处理,还可以在程序要向这个路径写入数据之前,创建出这个路径。import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.Scanner;public class ListRoots {private static final String LOG_BASE_PATH = "C:\\Users\HP\\Desktop\\";private static ArrayList<String> mfiles = new ArrayList<String>();/*** 得到给定路径下的目录或是文件* @param strPath* @throws Exception*/private static void displayDirsOrFiles(String strPath) throws Exception {try {File f = new File(strPath);if (f.isDirectory()) {File[] fList = f.listFiles();for (int j = 0; j < fList.length; j++) {if (fList[j].isDirectory()) {System.out.println("Directory is: "+ fList[j].getPath());displayDirsOrFiles(fList[j].getPath()); // 对当前目录下仍是目录的路径进行遍历}}for (int j = 0; j < fList.length; j++) {if (fList[j].isFile()) {String name = fList[j].getPath().toString();System.out.println("Filename is: " + name);mfiles.add(fList[j].getPath());}}}} catch (Exception e) {System.err.println("Error: " + e);}}/*** 向文件中写入数据* @param dirOrfiles* @throws IOException*/private static void writeDetailToFiles(ArrayList<String> dirOrfiles) throws IOException {SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd H:m:s");toFiles(getLogPath(), format.format(new Date()) + " — 检测到文件" + dirOrfiles.size() + "个:" + "\r\n");for (String file : dirOrfiles) {toFiles(getLogPath(), file + "\r\n");}toFiles(getLogPath(), "————————————————————————————————————————–\r\n");}/*** 获得写入数据的路径* @return*/private static String getLogPath() {SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");return LOG_BASE_PATH + format.format(new Date()) + ".txt";}/*** 向dir路径下写入数据data* @param path* @param data*/private static void toFiles(String path, String data) throws IOException {File file = new File(path);if (!file.exists()) {file.createNewFile();}FileWriter fw = new FileWriter(file, true);fw.write(data);fw.flush();fw.close();}public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("请输入待遍历目录路径(Format: F:\\a\\b):");String strPath = input.nextLine();try {displayDirsOrFiles(strPath.replace("\\", "\\\\"));writeDetailToFiles(mfiles);} catch (Exception e) {e.printStackTrace();}}}

5. 在Java中,如何用showOpenDialog默认打开某路径的,而不是打开C盘的Documents文件夹

我猜你应该是用了一个JFileChooser对象吧,其中有一个方法叫changeToParentDirectory()方法,该方法会将目录调整到当前目录的父目录,比如说C盘或者D盘,另外还有一个方法叫setCurrentDirectory(Filefile)方法,这个方法可以直接指定当前目录应该从哪开始。JFileChooserchoose=newJFileChooser();//使用父目录choose.changeToParentDirectory();choose.showOpenDialog(null);//使用指定目录choose.setCurrentDirectory(newFile("D:/Java"));choose.showOpenDialog(null);希望能帮到您。

6. java读取指定目录下的文件内容

publicclassReadFromFile{/***以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。*/(StringfileName){Filefile=newFile(fileName);InputStreamin=null;try{System.out.println("以字节为单位读取文件内容,一次读一个字节:");//一次读一个字节in=newFileInputStream(file);inttempbyte;while((tempbyte=in.read())!=-1){System.out.write(tempbyte);}in.close();}catch(IOExceptione){e.printStackTrace();return;}try{System.out.println("以字节为单位读取文件内容,一次读多个字节:");//一次读多个字节byte[]tempbytes=newbyte[100];intbyteread=0;in=newFileInputStream(fileName);ReadFromFile.showAvailableBytes(in);//读入多个字节到字节数组中,byteread为一次读入的字节数while((byteread=in.read(tempbytes))!=-1){System.out.write(tempbytes,0,byteread);}}catch(Exceptione1){e1.printStackTrace();}finally{if(in!=null){try{in.close();}catch(IOExceptione1){}}}}/***以字符为单位读取文件,常用于读文本,数字等类型的文件*/(StringfileName){Filefile=newFile(fileName);Readerreader=null;try{System.out.println("以字符为单位读取文件内容,一次读一个字节:");//一次读一个字符reader=newInputStreamReader(newFileInputStream(file));inttempchar;while((tempchar=reader.read())!=-1){//对于windows下,这两个字符在一起时,表示一个换行。//但如果这两个字符分开显示时,会换两次行。//因此,屏蔽掉,或者屏蔽。否则,将会多出很多空行。if(((char)tempchar)!=''){System.out.print((char)tempchar);}}reader.close();}catch(Exceptione){e.printStackTrace();}try{System.out.println("以字符为单位读取文件内容,一次读多个字节:");//一次读多个字符char[]tempchars=newchar[30];intcharread=0;reader=newInputStreamReader(newFileInputStream(fileName));//读入多个字符到字符数组中,charread为一次读取字符数while((charread=reader.read(tempchars))!=-1){//同样屏蔽掉不显示if((charread==tempchars.length)&&(tempchars[tempchars.length-1]!='')){System.out.print(tempchars);}else{for(inti=0;i<charread;i++){if(tempchars[i]==''){continue;}else{System.out.print(tempchars[i]);}}}}}catch(Exceptione1){e1.printStackTrace();}finally{if(reader!=null){try{reader.close();}catch(IOExceptione1){}}}}/***以行为单位读取文件,常用于读面向行的格式化文件*/(StringfileName){Filefile=newFile(fileName);BufferedReaderreader=null;try{System.out.println("以行为单位读取文件内容,一次读一整行:");reader=newBufferedReader(newFileReader(file));StringtempString=null;intline=1;//一次读入一行,直到读入null为文件结束while((tempString=reader.readLine())!=null){//显示行号System.out.println("line"+line+":"+tempString);line++;}reader.close();}catch(IOExceptione){e.printStackTrace();}finally{if(reader!=null){try{reader.close();}catch(IOExceptione1){}}}}/***随机读取文件内容*/(StringfileName){RandomAccessFilerandomFile=null;try{System.out.println("随机读取一段文件内容:");//打开一个随机访问文件流,按只读方式randomFile=newRandomAccessFile(fileName,"r");//文件长度,字节数longfileLength=randomFile.length();//读文件的起始位置intbeginIndex=(fileLength>4)?4:0;//将读文件的开始位置移到beginIndex位置。randomFile.seek(beginIndex);byte[]bytes=newbyte[10];intbyteread=0;//一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。//将一次读取的字节数赋给bytereadwhile((byteread=randomFile.read(bytes))!=-1){System.out.write(bytes,0,byteread);}}catch(IOExceptione){e.printStackTrace();}finally{if(randomFile!=null){try{randomFile.close();}catch(IOExceptione1){}}}}/***显示输入流中还剩的字节数*/(InputStreamin){try{System.out.println("当前字节输入流中的字节数为:"+in.available());}catch(IOExceptione){e.printStackTrace();}}publicstaticvoidmain(String[]args){StringfileName="C:/temp/newTemp.txt";ReadFromFile.readFileByBytes(fileName);ReadFromFile.readFileByChars(fileName);ReadFromFile.readFileByLines(fileName);ReadFromFile.readFileByRandomAccess(fileName);}}

7. java中如何打开一个相对路径的文件

就是当前的工作目录啊。比如你的JAVA程序和file.txt这个文件在同一目录,相对路径就是 \\file.txt

8. java如何打开目录下特定文件

public class TestByteIO { public static void main(String[] args) { File f = new File(“c:\\temp.txt”); //创建文件对象try { // 通过文件对象创建文件输入流 FileInputStream filein = new FileInputStream(f); //创建字节数组,用于接收从文件中读取的字节 byte buf[] = new byte[1024]; String instr = ""; //接收字节转化的字符串 int length = filein.read(buf); instr = new String(buf,0,length);//将字节转化成字符串 System.out.println(instr); filein.close(); //关闭输入流 } catch (IOException ex) { ex.printStackTrace(); } }}

9. java 怎么获取指定路径下的文件

//根据你的要求修改了一下代码,现在已经能将某文件夹下的所有指定类型文件复制到//指定文件夹下了import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;public class ReadFiles {public static final String FILTER = "xml";public static final String SRC_DIR = "E:\\StudyData";// 待扫描的文件夹public static final String DES_DIR = "E:\\testdata";// 复制后的目标文件夹public static void main(String[] args) {long a = System.currentTimeMillis();scanDir(SRC_DIR, DES_DIR);System.out.println("共花费时间:"+(System.currentTimeMillis() – a)/1000+"秒");}public static void scanDir(String srcPath, String desPath) {File dir = new File(srcPath);File[] files = dir.listFiles();if (files == null)return;for (int i = 0; i < files.length; i++) {if (files[i].isDirectory()) {scanDir(files[i].getAbsolutePath(), desPath);} else {String strFileName = files[i].getAbsolutePath().toLowerCase();File(strFileName, desPath + files[i].getName());}}}public static void File(String srcName, String destName) {if (srcName.endsWith(FILTER)) {System.out.println("正在复制文件 "+srcName+" 至 "+destName);try {BufferedInputStream in = new BufferedInputStream(new FileInputStream(srcName));BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destName));int i = 0;byte[] buffer = new byte[2048];while ((i = in.read(buffer)) != -1) {out.write(buffer, 0, i);}out.close();in.close();} catch (Exception ex) {ex.printStackTrace();}}}}

10. java如何读取指定目录下的txt文件

你好代码如下,我调试通过了,希望我的回答对你有帮助!

代码说明,要查询是否存在''java"。在D:盘建一个word.txt的文档,里面写一些单词,保存。运行如下代码会判断是否存在“java”这个单词。

packaget;importjava.io.BufferedReader;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.IOException;importjava.io.InputStreamReader;publicclassTestRead{publicstaticvoidmain(String[]args)throwsIOException{FileInputStreamfis=newFileInputStream("d:/word.txt");InputStreamReaderisr=newInputStreamReader(fis);BufferedReaderbr=newBufferedReader(isr);Strings;intcount=0;while((s=br.readLine())!=null){String[]s1=s.split("");for(inti=0;i<s1.length;i++){if("java".equals(s1[i])){System.out.println("存在单词"+s1[i]);count++;}}}if(count==0){System.out.println("不存在java这个单词");}}}


赞 (0)