在java开发过程中,经常需要读写文件,写对文件的相对路径显得尤为重要。
第一部分:/ 和 .
首先来看 / 和 . 对应的路径是什么:
File file = new File("/");
System.out.println("/ 代表的绝对路径为:" + file.getAbsolutePath());
File file1 = new File(".");
System.out.println(". 代表的绝对路径为" + file1.getAbsolutePath());
运行上面的代码可以得到结果如下:
/ 代表的绝对路径为:D:
. 代表的绝对路径为D:\eclipse-workspace\SrcTest.
显然,/ 代表的路径是根目录;. 代表的路径是当前Java项目的根目录。
第二部分:读取文件的三种方式
Java读取文件的一般方式有三种:
- new File();
- 使用类的相对路径;
- 使用线程的类加载器;
这三种方式是最普通,最通用的方式,框架里面用注解读取配置文件不包括在这里。
第三部分:三种方式对应的相对路径
在写三种方式的代码的时候,先有一些准备工作:
1.先新建了三个新的.txt文件,在不同的目录层级,里面写上了该文件的绝对位置。
test1: D:\eclipse-workspace\SrcTest\src\test1.txt
test2: D:\eclipse-workspace\SrcTest\src\test\test2.txt
test3: D:\eclipse-workspace\SrcTest\test3.txt
2.写了一个静态方法,功能是读取文件内容。
public static void readContext(File file) {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String len = null;
while ((len=br.readLine())!=null){
System.out.println(len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
接下来就是正题了。
1.new File()
这是一种比较暴力的方法,三个txt文件的路径如下:
File file = new File("src/test1.txt");
File file = new File("src/test/test2.txt");
File file = new File("test3.txt");
由此可见,在这种方法里面,“”代表的是Java项目的根目录。
2.使用类的相对路径
这是常用的方法。这种方法里面,“/”代表的是Java项目bin目录,因为在加载项目的时候,src里面的所有文件都会被加载到bin目录中,所以这里不讨论放在项目根目录下的test3.txt文件的读取。
test1.txt和test2.txt文件的路径如下:
File file = new File(ResourceRead.class.getResource("/test1.txt").getFile());
File file = new File(ResourceRead.class.getResource("/test/test2.txt").getFile());
3.使用线程的类加载器
这种方法与第二种相似,通过代码来看:
File file = new File(Thread.currentThread().getContextClassLoader().getResource("test1.txt").getFile());
File file = new File(Thread.currentThread().getContextClassLoader().getResource("test/test2.txt").getFile());
可以看出,“”代表的是Java项目bin目录。