java 从不在我的类路径中的路径加载属性文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13958980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:34:35  来源:igfitidea点击:

Loading a properties file from a path that is not in my class path

javaproperties

提问by user63898

Hmm simple task but how do i load properties file from path that is not in my class path?

嗯,简单的任务,但如何从不在我的类路径中的路径加载属性文件?

for example:i have simple java file that i execute like this : foo.jar d:/sample/dir/dir/app1.properties and in the code i do :

例如:我有一个简单的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;
        }
     }

where propePath is : d:/sample/dir/dir/app1.properties
and InputStream in is always null. why does this happen?

其中 propePath 是:d:/sample/dir/dir/app1.properties
并且 InputStream in 始终为空。为什么会这样?

回答by Perception

The only resources that can be loaded by Classloader.getResourceAsStreamare ones in the class (loaders) path. To read properties from an arbitrary path use one of the loadfunctions of the Propertiesclass itself.

唯一可以加载的资源是Classloader.getResourceAsStream类(加载器)路径中的资源。要从任意路径读取属性,请使用Properties类本身的load功能之一。

final Properties props = new Properties();
props.load(new FileInputStream(filePath));