简体   繁体   中英

Java : How to modify config.properties in runtime?

I have a key which has a value.

autoFixBasePath=C:/myTest

I would like the autoFixBasePath to be appended to some of the keys declared down:

So I am trying to set the value of autoFixBasePath at the start and then modify the config file:

    try {
        PropertiesConfiguration config = new PropertiesConfiguration("config.properties");
        config.setProperty("autoFixBasePath", args[2]);
        config.save();
    }catch (Exception exception){

    }

This works locally, but when using maven assembly plugin, I have put the config file inside jar, there it fails.

How can I do this?

Read the properties file from, for example, %USER_PROFILE%\AppData\Local\YourApp\config.properties (on Windows) or ~/.yourapp/config.properties (on Unix). If that file does not exist at app startup, copy the default settings file from within your JAR to the location named above.

(Although I question how good your approach is. Users of command line tools generally expect that the tool will default to a certain behaviour, and that any command line parameters passed to it will only take effect on that single invocation of the tool. But hey, that's your choice.)

You could also use the Preferences API, documented here: https://docs.oracle.com/javase/8/docs/technotes/guides/preferences/overview.html - which takes care of OS-specific paths and changes at runtime in a way that Properties do not (because those are intended to be passed to the program at startup, and to be immutable from there on.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM