1

I would like to persist some properties to property-file in case they were changed during a program run. Now I am trying to do so:

Properties properties = new Properties(); try (FileInputStream in = new FileInputStream("classpath:app.properties")) { properties.load(in); } catch (IOException e) { logger.error("", e); } properties.setProperty("word", "abc"); try (FileOutputStream out = new FileOutputStream("classpath:app.properties")) { properties.store(out, null); } catch (IOException e) { logger.error("", e); } 

But it doesn't seem to work. What am I doing wrong?

1
  • Well, I tried to do the same, and noticed that my properties wasn't actually loaded. I couldn't get props I've defined in the file. Commented Oct 30, 2014 at 20:02

3 Answers 3

3

To be able to read and write properties file, which are in the resources folder (in standard maven project structure) you can use this:

// of course, do not forget to close the stream, after your properties file has been read. properties.load(Runner.class.getClassLoader().getResourceAsStream("app.properties")); 

After you modified the properties file, you can use something like:

Runner.class.getClassLoader().getResource("app.properties").getFile() 

to get absolute path to you file.

P.S. Just to be sure you're checking correct file. You shouldn't check file that is in your resources folder. The modified file will be placed in the root folder with you classes, like target or out.

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

Comments

1

If the file is in the same directory as your program, you don't need the classpath part.

Properties properties = new Properties(); try (FileInputStream in = new FileInputStream("app.properties")) { properties.load(in); } catch (IOException e) { logger.error("", e); } properties.setProperty("word", "abc"); try (FileOutputStream out = new FileOutputStream("app.properties")) { properties.store(out, null); } catch (IOException e) { logger.error("", e); } 

Otherwise if the file is within your jar, you would have to repackage the jar

Comments

0

If you want to stick to properties file handling through class path - you can certainly use below code as it is , i think it is simplest way of handling file in class path for both - reading and writing purpose

try{ InputStream in = this.getClass().getResourceAsStream("/suggest.properties"); Properties props = new Properties(); props.load(in); in.close(); URL url = this.getClass().getResource("/suggest.properties"); File fileObject = new File(url.toURI()); FileOutputStream out = new FileOutputStream(fileObject); props.setProperty("country", "america"); props.store(out, null); out.close(); }catch(Exception e) { System.out.println(e.getMessage()); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.