java 在java应用程序中读取外部属性文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15727676/
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
Read external property file in java application
提问by user2210071
I want to load a property file from outside the web application.The code to get property file is shown below.
我想从 Web 应用程序外部加载一个属性文件。获取属性文件的代码如下所示。
Properties p = new Properties();
p.load(this.getClass().getClassLoader().getResourceAsStream("a.properties"));
I'm using tomcat server and I want to place the property file inside the tomcat server.Where I can place it in the server inorder to available it in the class path while running the application? I don't want to change the above code because I have to run the same application indifferent server also
我正在使用 tomcat 服务器,我想将属性文件放在 tomcat 服务器中。我可以将它放在服务器中的哪个位置,以便在运行应用程序时在类路径中使用它?我不想更改上面的代码,因为我也必须运行相同的应用程序 indifferent 服务器
回答by joan
I recommend the first option. Put the a.propertiesin the classpath. Then load with:
我推荐第一个选项。将a.properties放在类路径中。然后加载:
Properties properties = new Properties();
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("a.properties"));
This way you can load properties relative tot the "root" of the classpath. Tt's recommended to use the ClassLoader as returned by Thread.currentThread().getContextClassLoader() for this.
通过这种方式,您可以加载相对于类路径的“根”的属性。为此,建议使用 Thread.currentThread().getContextClassLoader() 返回的 ClassLoader。
回答by Biswajit
There are basically three ways: The remaining portion you can see in Where to place and how to read configuration resource files in servlet based application?
基本上有三种方式: 剩下的部分您可以 在基于 servlet 的应用程序中放置和如何读取配置资源文件中看到?