11

Is it possible to create a new properties file and add keys and values in run time? I want to add new keys to properties file depending on user input while installing my application. I checked out Java Properties class but it seem it can set values to existing keys but can not add new keys to properties file.

Olcay Ertaş
  • 5,987
  • 8
  • 76
  • 112

1 Answers1

14

You can add new properties just by calling setProperty with a key which doesn't currently exist. That will only do it in memory though - you'll have to call store again to reflect the changes back to a file:

Properties prop = new Properties();
prop.load(...); // FileInputStream or whatever

prop.setProperty("newKey", "newValue");
prop.store(...); // FileOutputStream or whatever
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Its not reflecting even i store the property changed, any idea? – Premanand K Aug 05 '16 at 20:14
  • @PremanandK: I'm afraid I don't understand your comment at all. Perhaps you should ask a new question with a [mcve]. – Jon Skeet Aug 05 '16 at 20:16
  • I saved my property changes as "prop.store(...);", but its not reflecting. ie. i am not seeing my changes in my properties file. Thanks for replying @Jon Skeet – Premanand K Aug 05 '16 at 20:18
  • @PremanandK: Again, ask a new question with a [mcve] so we can reproduce it. I certainly can't tell what's wrong from a one sentence description. – Jon Skeet Aug 05 '16 at 20:21
  • http://stackoverflow.com/questions/38797349/property-files-changes-not-reflected-after-storing-in-java - raised as the question. – Premanand K Aug 05 '16 at 20:30