How to overwrite one property in .properties without overwriting the whole file?

前端 未结 8 2045
逝去的感伤
逝去的感伤 2020-12-01 16:11

Basically, I have to overwrite a certain property in a .properties file through a Java app, but when I use Properties.setProperty() and Properties.Store() it overwrites the

相关标签:
8条回答
  • 2020-12-01 16:40

    You can use PropertiesConfiguration from Apache Commons Configuration.

    In version 1.X:

    PropertiesConfiguration config = new PropertiesConfiguration("file.properties");
    config.setProperty("somekey", "somevalue");
    config.save();
    

    From version 2.0:

    Parameters params = new Parameters();
    FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
        new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
        .configure(params.properties()
            .setFileName("file.properties"));
    Configuration config = builder.getConfiguration();
    config.setProperty("somekey", "somevalue");
    builder.save();
    
    0 讨论(0)
  • 2020-12-01 16:43

    Properties files are an easy way to provide configuration for an application, but not necessarily a good way to do programmatic, user-specific customization, for just the reason that you've found.

    For that, I'd use the Preferences API.

    0 讨论(0)
提交回复
热议问题