通过路径读文件一般就3种方式,但他们完全不同:
1. File myFile=new File("myfile.txt");
上面这么写是从当前路径读文件,当前路径指启动当前Java进程的路径,不同的情况这个路径都不一样,在Eclipse里一般是当前项目的路径,在 Servlet里一般就是Servlet容器的路径。在Java中相对路径,相对的是JVM的启动路径,而一般来说就是在项目名称下启动的。
这个路径的绝对值可以通过System.getProperty(“user.dir”))取到。
这个方法同时可以通过绝对路径取文件,
File myFile=new File("D:\temp\myfile.txt"); File myFile=new File("/usr/user1/myfile.txt");
另一个例子

public class Demo1 { public static void main(String[] args) throws Exception{ File f1 = new File("test1.txt"); File f2 = new File("./test2.txt"); File f3 = new File("src/test3.txt"); File f4 = new File("test4.txt"); System.out.println(f1.exists()+":"+f1.getCanonicalPath()); System.out.println(f2.exists()+":"+f2.getCanonicalPath()); System.out.println(f3.exists()+":"+f3.getCanonicalPath()); System.out.println(f4.exists()+":"+f4.getCanonicalPath()); } }
输出:
true:D:\spam\path\test1.txt true:D:\spam\path\test2.txt true:D:\spam\path\src\test3.txt false:D:\spam\path\test4.txt
说明:
①从示例中我们可以看到所有的文件都是相对于D:\spam\path这个路径建立的。 ②"./test2"与"test1"表示的都是一样的语义,相对与当前JVM的启动目录 ③"../test"表示相对于当前目录的上一级目录 ④test4告诉我们File的语义表示的仅仅是一个路径
2. InputStream myFileStream = this.getClass().getResourceAsStream("myfile.txt");
从当前类所在路径读文件, myfile.txt应该是和当前这个类在同一个目录中的文件。如果路径前放了个”/”, 如this.getClass().getResourceAsStream(“/myfile.txt”),那就是从当前classpath开始读了
3.InputStream myFileStream = this.getClass().getClassLoader().getResourceAsStream("myfile.txt");
这个容易和第2种混淆,它是指从classpath开始找文件,前面加不加”/”都一样,其实它相当与this.getClass().getResourceAsStream(“/myfile.txt”), 与这个有相同效果的还有
Thread.currentThread().getContextClassLoader().getResourceAsStream("myfile.txt")或 Thread.currentThread().getContextClassLoader().getResourceAsStream("/myfile.txt") ClassLoader.getSystemResource("myfile.txt")或 ClassLoader.getSystemResource("/myfile.txt")
下面这个代码
package com.test.path; import java.io.File; class TestPath { public static void main(String[] args) throws Exception { System.out.println(Thread.currentThread().getContextClassLoader().getResource("")); System.out.println(TestPath.class.getClassLoader().getResource("")); System.out.println(ClassLoader.getSystemResource("")); System.out.println(TestPath.class.getClassLoader().getResource("")); System.out.println(TestPath.class.getResource("")); System.out.println(TestPath.class.getResource("/")); System.out.println(new File("").getAbsolutePath()); System.out.println(System.getProperty("user.dir")); } }
它的输出:
file:/C:/TestArena/bin/ file:/C:/TestArena/bin/ file:/C:/TestArena/bin/ file:/C:/TestArena/bin/ file:/C:/TestArena/bin/com/test/path/ file:/C:/TestArena/bin/ C:\TestArena C:\TestArena