简单的说,在使用inputstream读取文件的时候,所谓的相对路径是相对于工程目录的,绝对路径当然是对于盘符根目录来说。
例如:
代码
packageio;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStream;publicclassInputStreamDemo {publicstaticvoidmain(String[] args)throwsIOException {
File root=newFile("");
System.out.println(root.getAbsolutePath());
File f=newFile("src/main/java/io/test.properties");
System.out.println(f.exists());
System.out.println(f.getAbsolutePath());
InputStream in=newFileInputStream("src/main/java/io/test.properties");byte[] b=newbyte[255];while(in.read(b)!=-1) {
System.out.println(newString(b));
}
}
}
输出结果:
E:\EclipseProjects\demoSet
true
E:\EclipseProjects\demoSet\src\main\java\io\test.properties
tt = "good"
E:\EclipseProjects\demoSet
true
E:\EclipseProjects\demoSet\src\main\java\io\test.properties
tt = "good"
我只是在和该类同级的地方放了一个test.properties,里面写了tt="good",用相对路径的话只能把目录写全,我本来以为直接写test.properties就可以了。
还有一种方法是直接从类路径中读取
代码
packageio;importjava.io.IOException;importjava.io.InputStream;publicclassResourceDemo {publicstaticvoidmain(String[] args)throwsIOException {
InputStream in=ResourceDemo.class.getResourceAsStream("test.properties");byte[] b=newbyte[255];while(in.read(b)!=-1) {
System.out.println(newString(b));
}
in.close();
}
}
使用getResourceAsStream方法的相对路径就在该类的目录下,而写上路径"/test.properties"系统就会到classpath的根目录底下去寻找。
相比较而言,getResourceAsStream方法更好更ok,推荐使用