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); 
3
  • What do you mean by "doesn't work"? Is the file created but is blank? Do you get an exception? Commented May 28, 2014 at 18:48
  • Do you mean like updating the jar file that contains the properties file? Commented May 28, 2014 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. Commented May 28, 2014 at 18:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.