java路径分为相对路径与绝对路径:
java project 目录结构如下:
1.通过getResourceAsStream()方法获取路径:
1)如果已"/"开头,表示从classpath路径开始查找,如果想取到test2.properties的值。可以这样写
@Test
public void test3(){
try {
Properties pro = new Properties();
InputStream in = test.class.getResourceAsStream("/com/cf/test2.properties");
pro.load(in);
String filePath = pro.getProperty("filePath");
System.out.println(filePath);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
得到结果:helloworld_test2;
2)如果不以"/"开头,表示从test.java包内查找相对路径,如果想取到test2.properties的值。可以这样
InputStream in = test.class.getResourceAsStream("test2.properties");
其余代码同上。
得到结果:helloworld_test2;
2.通过File file加载文件,代码如下
@Test
public void test4(){
File f = new File("/com/cf/test2.properties");
if(f.exists()){
try {
Properties pro = new Properties();
InputStream in = new FileInputStream(f);
pro.load(in);
String filePath = pro.getProperty("filePath");
System.out.println(filePath);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
System.out.println("没找到");
}
}
输出:没找到
2)如果以相对路径查找test2.properties,代码如下
File f = new File("src/com/cf/test2.properties");
其余代码同上,
输出:helloworld_test2;
通过以上测试发现:
通过test.class.getResourceAsStream("")获取绝对路径,可以通过在开头加"/"实现,查找路径为 classpath;如果不加"/",相对路径查找,只是从test.java包内查找;
通过File f = new File(""),如上加上"/"查找test2.properites ,没有找到文件;如果以相对路径查找,是以项目根路径为起点开始查找。
暂时记录如下,以后会陆续补充。