开发者

properties file not working inside jar

开发者 https://www.devze.com 2023-01-18 19:38 出处:网络
I am having issues with properties file when I try to make my standalone Java aplication a runnable jar.

I am having issues with properties file when I try to make my standalone Java aplication a runnable jar. I have 2 properties file, depending upon the machine where its running one gets initialized. Inside eclipse it was working fine. I was using:

Properties configProps = new Properties();
....
if(machine1)
....
configProps.load(Config.class.getResourceAsStream("machine1.properties"));
else
configProps.load(Config.class.getResourceAsStream("mach开发者_开发问答ine2.properties"));

It was working as Config.java and properties were in the same package. On top of that I have log4j properties located on the root of the project. That is also not working whne i made Jar.

How to handle the current sutuation.I know putting properties file outside jar is good idea. How do I accomplish this.

Please help.


Putting the properties file outside of the jar is only a good idea if you need to write to that property file (it's for configuration). Given your naming, I assume it is for configuration.

For reading only, your method is fine if the properties file is properly being packaged in the Jar. Is it? Have you peaked at the contents using jar tf MyJar.jar? Does it show your properties file at the correct path?

Where to store configuration files is a broader issue. Here's a good SO article that examines a few aspects of it (namely where to put it): What is the proper way to store app's conf data in Java?

It seems to me you want to choose a location (see the above article). Once you've done that, the first time the application is run you should load the default properties from your Jar file as you are trying to do, then immediately save them to the location you've chosen. Then, and afterwards, read from and write to that location instead. You will need to use a FileInputStream/FileOutputStream.


Try adding a manifest to your JAR's META-INF with Class-Path set appropriately.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号