Reputation: 95
I'm trying to change some values in my config.properties file.There is change in values when I set them but it doesn't get saved. here is my code
public class Config {
String filename = "config.properties";
public void displayConfig() throws IOException {
Properties prop = new Properties();
InputStream input = null;
input = getClass().getClassLoader().getResourceAsStream(filename);
if (input == null) {
System.out.println("unable to find " + filename);
return;
}
prop.load(input);
System.out.println();
System.out.println(prop);
Enumeration<?> e = prop.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = prop.getProperty(key);
System.out.println(key + " : " + value);
}
return;
}
public void setConfig() throws Exception {
File filename = new File("config.properties");
Properties prop = new Properties();
FileInputStream in = new FileInputStream(filename);
prop.load(in);
in.close();
FileOutputStream out = new FileOutputStream("config.properties");
prop.setProperty("db", "csv");
prop.setProperty("user", "tej");
prop.setProperty("password", "54321");
prop.store(out, null);
out.close();
System.out.println();
System.out.println(prop);
}
}
and the output when I call displayConfig,setConfig,displayConfig is like
{user=localhost, db=dtcc, password=12345}
db : dtcc
user : localhost
password : 12345
{user=tej, db=csv, password=54321, key=value}
{user=localhost, db=dtcc, password=12345}
db : dtcc
user : localhost
password : 12345
Upvotes: 1
Views: 1740
Reputation: 691705
Well, that's quite expected, since displayConfig()
doesn't load its properties from the same location as setConfig()
.
displayConfig()
loads them from the resource config.properties at the root of the classpath, and setConfig loads and saves them in a file in the current directory.
BTW; even if the current directory happens to be in the classpath, I think getResourceAsStream()
caches the stream content the first time it's called.
Choose your poison: either you want readable and writable files, and you should use file IO, or you want read-only resources loaded from the classpath, and you should use getResource[AsStream]
. Don't mix both.
Upvotes: 3