Confused about java properties file location

☆樱花仙子☆ 提交于 2019-11-30 06:01:59

The typical way of handling this is to load the base properties from your embedded file, and allow users of the application to specify an additional file with overrides. Some pseudocode:

Properties p = new Properties();
InputStream in = this.getClass().getResourceAsStream("c.properties");
p.load(in);

String externalFileName = System.getProperty("app.properties");
InputStream fin = new FileInputStream(new File(externalFileName));
p.load(fin);

Your program would be invoked similar to this:

java -jar app.jar -Dapp.properties="/path/to/custom/app.properties"
prajeesh kumar

First keep the default properties in your properties file, which gets packed into the jar. When the application starts try reading a same named properties file from some default location in filesystem, preferrable the user's home folder which you can obtain by System.getProperty("user.home");. If the file exists at the filesystem load it, if it doesn't exist then load your packed properties file and write a copy to the filesystem.

So if your properties file name is myprops.properties, initially only your jar file will contain it. When the application starts up it will check whether /home/xyz/myprops.properties file exists. Since it doesn't, it will read the packed properties file and write a copy to /home/xyz/myprops.properties file. From next time onwards, it will read from /home/xyz/myprops.properties.

Why not pass the location of the properties file as a command line argument (following a flag)? if it's not present, then use the default one in the jar file.

Jeremy Ross

You're loading the properties file from the class path. I'd suggest something like this:

Properties location

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