Loading Properties from a JAR file (java 1.6)

放肆的年华 提交于 2019-12-30 14:29:09

问题


I manually inject a properties file inside a jar. How to load properties from a jar file before java 1.7 ? I tried many workarounds and nothing worked so far.

There's plenty questions about it, but everything is focused on ClassLoader methods from java 1.7.


回答1:


When you have a properties file inside your classpath or inside your jar file it becomes a resource. Any other case is a simple file.

What you need to do, before you package your jar file, is add to your classpath the folder where the properties files are (i.e myproject/src/main/resources/) then wherever you do a

Properties properties = new Properties(); 
properties.load(MyClass.class.getResourceAsStream("/yourPropsFileName"));

it will load it!

Although, if you are using an external property file you can also load it by using:

Properties properties = new Properties();
properties.load(new FileInputStream("extenalPropsFileLocation"));

Hope it helps!




回答2:


From some class, call:

getClass().getResourceAsStream("/path/to/props.props")

Make sure that the path matches up with a classpath location.



来源:https://stackoverflow.com/questions/25999277/loading-properties-from-a-jar-file-java-1-6

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!