简单的任务,但如何从不在我的类路径中的路径加载属性文件?
例如:我有简单的java文件,我执行如下: foo.jar d:/sample/dir/dir/app1.properties 在我做的代码中:
public boolean InitConfig(String propePath) {
prop = new Properties();
try {
InputStream in = this.getClass().getClassLoader().getResourceAsStream(propePath);
prop.load(in);
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
其中propePath是:d:/sample/dir/dir/app1.properties
和InputStream in始终为null。
为什么会这样?
答案 0 :(得分:21)
Classloader.getResourceAsStream
可以加载的唯一资源是类(加载器)路径中的资源。要从任意路径读取属性,请使用Properties类本身的load
函数之一。
final Properties props = new Properties();
props.load(new FileInputStream(filePath));