3

I am writing a java web application that reads properties from a .properties file. Since I do not know the absolute path of the .properties file, because it depends on the environment the application will run on in the future, I have to load it with "getClass().getResourceAsStream":

Properties props = new Properties();
props.load(getClass().getResourceAsStream("test.properties"));
message = props.getProperty("testdata");

This works as expected. Now I want to change the value for testdata in the file. But I cannot open an Outputstream to write to, because I still don't know the path of the .properties file.

props.setProperty("testdata", "foooo");
props.store(new FileOutputStream("?????"), null);

Is there a way to get the path of the file or can I use the established Properties-object somehow? Any ideas are welcome that allow me to change the .properties file.

Demento
  • 4,039
  • 3
  • 26
  • 36

2 Answers2

2

You can get an URL by using getResource() rather than using getResourceAsStream()

You can then use that URL to read from and write to your properties file.

File myProps = new File(myUrl.toURI());
FileInputStream in = new FileInputStream(myProps); 

Etc.

Brian Roach
  • 76,169
  • 12
  • 136
  • 161
-3

The Properties class includes a store method that can be used to save the properties back to the stream that was read in getClass().getResourceAsStream("test.properties").

fipple
  • 360
  • 1
  • 5
  • The store method requires a FileOutputStream, but getClass().getResourceAsStream("test.properties") only gives me a FileInputStream. If those cannot be converted in a sane way, this approach fails. – Demento Apr 08 '11 at 00:31