2

To load a properties file from classpath, we can simply do:

InputStream inputStream = CommonUtils.class.getClassLoader().getResourceAsStream("com/abc/resources/config.properties");
prop.load(inputStream);

After above step, all properties are correctly loaded. But how can I change a property and save it back to the same file on the fly? (Below doesn't work)

OutputStream outputStream = new FileOutputStream("com/abc/resources/config.properties");
prop.setProperty(key, value);
prop.store(outputStream, null);
Kevin
  • 2,191
  • 9
  • 35
  • 49
  • What do you mean by "doesn't work"? Is the file created but is blank? Do you get an exception? – Greg Case May 28 '14 at 18:48
  • Do you mean like updating the jar file that contains the properties file? – Eng.Fouad May 28 '14 at 18:49
  • The file locates in the project, as the first part shows, so I use the `class.getClassLoader()` to locate the file. But if I change something and I want to write it back, how can I do that? Thanks. – Kevin May 28 '14 at 18:59

1 Answers1

1

You can not a write to a resource loaded this way.

I would recommend that when your application starts up for the first time it load the defaults properties from the jar file and persist in a well known location. Then when the application starts it reads the properties from this location. This stack overflow question has more details about how and where to persist.

Community
  • 1
  • 1
ditkin
  • 6,774
  • 1
  • 35
  • 37
  • Actually, this is also my solution... but I was wondering if there is any better way other than making a copy of the original properties file. Thanks. – Kevin May 28 '14 at 19:07