Successfully accessed a property file via getResourcestream and read using fileinputstream. Now I need to overwrite the same file after appending a new property
Problem: stuck getting path of the same file which is required by fileoutputstream for overwriting.
property file is in src/main/resources. and trying to update from src/main/java/com/web/my.class
Properties prop = new Properties();
InputStream in = getClass().getClassLoader().getResourceAsStream("dme.properties");
FileOutputStream out = null;
try {
prop.load(in);} // load all old properties
catch (IOException e) {}
finally {try { in.close(); } catch (IOException e) {} }
prop.setProperty("a", "b"); //new property
try {
out = new FileOutputStream("dme.properties");
prop.store(out, null);} //overwrite
catch (IOException e) {}
finally {try {out.close();} catch (IOException e) {} }
}
Instead of getting the InputStream
, you can get the resource URL
and use that to read and write with your file from src/main/resources
:
Properties properties = new Properties();
File file = new File(this.getClass().getResource("/dme.properties").toURI());
try (InputStream is = new FileInputStream(file)) {
properties.load(is);
}
properties.setProperty("a", "b");
try (OutputStream os = new FileOutputStream(file)) {
properties.store(os, null);
}