从 Java 类路径加载 .properties 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36686749/
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
Load .properties file from Class Path in Java
提问by Developer
I have to access my .properties file from its class path. Currently I am accessing that from the resources folder directly. But now I want to acess that from the class path.
我必须从它的类路径访问我的 .properties 文件。目前我直接从资源文件夹访问它。但现在我想从类路径访问它。
Current Code:
当前代码:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
try {
properties.load(new FileInputStream(
"src/resources/config.properties"));
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
rate.add(value);
}
}
}
Path of the file is :src/resources/config.properties
文件路径为:src/resources/config.properties
For deploying the code we are creating war file of the complete project.
为了部署代码,我们正在创建完整项目的 war 文件。
Please suggest how can we get this file from the class path.
请建议我们如何从类路径中获取此文件。
回答by Ataur Rahman Munna
If your config.properties
file reside on your same package of your java class then just use,
如果您的config.properties
文件驻留在 Java 类的同一个包中,则只需使用,
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config.properties");
If you put the properties file in any package, then use the package name also
如果您将属性文件放在任何包中,那么也要使用包名
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("com/your_package_name/config.properties");
So the compete code be like,
所以竞争代码就像,
try {
Properties configProperties = new Properties();
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("resources/config.properties");
configProperties.load(inputStream);
}
catch(Exception e){
System.out.println("Could not load the file");
e.printStackTrace();
}
UPDATE :For better understanding see the image.
更新:为了更好地理解,请参见图像。
回答by Wizbot
You can load file from classpath using this
您可以使用此从类路径加载文件
this.getClass().getClassLoader().getResourceAsStream("config.properties");
If you are dealing with .properties
files you should consider using ResourceBundle
如果您正在处理.properties
文件,您应该考虑使用ResourceBundle
回答by Raman Shrivastava
final Properties properties = new Properties();
try (final InputStream stream =
this.getClass().getResourceAsStream("somefile.properties")) {
properties.load(stream);
}