我的开发环境为Eclipse,代码为:
public class Test { public static void main(String[] args) {
System.out.println(System.getProperty("user.dir"));
System.out.println(System.getProperty("java.class.path"));
Test test = new Test();

try {
test.getMsg1();
} catch (IOException e) {
}

try {
test.getMsg2();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
} public void getMsg1() throws IOException {
Properties properties = new Properties();
InputStream is = getClass().getResourceAsStream("test.properties");
properties.load(is); System.out.println(properties.getProperty("str"));
} public void getMsg2() throws IOException, FileNotFoundException {
Properties properties = new Properties();
InputStream fis = new FileInputStream("test.properties");
properties.load(fis); System.out.println(properties.getProperty("str"));
}
}其中user.dir的值为D:\eclipse\workspace\Test
java.class.path的值为D:\eclipse\workspace\Test\bintest.properties在项目文件的根目录(根据user.dir的值而设),这里同样用的是相对路径,为什么
getMsg1()会提示文件不存在,而getMsg2()又可以取到值,不是相对路径是根据user.dir值定的么,用getClass().getResourceAsStream("test.properties");取的文件需要放在class文件所在目录下方可,这是怎么回事。另外,上述代码如果改为绝对路径的写法:InputStream is = getClass().getResourceAsStream("/test.properties");及InputStream fis = new FileInputStream("/test.properties");前者要求将文件放置在java.class.path(即项目的bin文件夹下),后者要求放在程序所在盘符的根目录下(即D盘根目录下),这又是怎么回事。难道InputStream和它的子类FileInputStream的参数对于相对路径和绝对路径有所不同?(附,File类及Reader的子类路径的写法和FileInputStream的相同,就这里的InputStream不同)还望大家解惑,谢谢!

解决方案 »

  1.   

    我建了一个项目Test。
    user.dir       =E:\JavaStudio\TheSource\Test
    java.class.path=E:\JavaStudio\TheSource\Test测试1:
    Test.java和test.properties放在E:\JavaStudio\TheSource\Test目录下,运行成功。测试2:
    创建包resourcepath,把两个文件移动的resourcepath,运行,TestMsg1可以,TestMsg2不行。
    ------------------------------------------
    这样看FileInputStream("test.properties")是以user.dir为基路径,所以test1可以找到文件,而test2却不行。至于getClass().getResourceAsStream("test.properties"),是由class的位置决定的,你可以参考APISpec中对Class和ClassLoader和说明。
    ------------------------------------------
    我们的结果不一致应该与test.properties的位置有关,但原理是一致的。