Reputation: 151
I have a standard Java application that reads configuration properties at start-up time, which work fine. However, I would like to update the configuration properties at execution time without compiling the code each time. How would I go about doing that.
e.g code:
Properties py = new Properties();
InputStream ins;
String prepName = "config.properties";
ins = getClass().getClassLoader().getResourceAsStream(prepName);
if (ins == null) {
System.err.println("Couldn't find the file!");
return "Error";
}
py.load(ins);
String message = py.getProperty("msg");
resources/config.properties
msg=testMessage
If I want to change message dynamically, how would I do it?
Upvotes: 0
Views: 398
Reputation: 4767
The WatchService referenced in Leo's comment looks interesting. I have done this pre-Java 7 by using a Properties object and a worker thread that checks the file modification timestamp every 15 seconds (or so). If the timestamp of the file changes, reload the Properties object from the filesystem.
Something like:
Properties py = new Properties();
long lastModMillis = 0L;
long modMillis = file.lastModified() // to get the file modification time
if (modMillis != lastModMillis)
{
// reload data
FileInputStream fis = ...
py.clear();
py.load(fis);
lastModMillis = modMillis;
}
(didn't include worker thread code)
Be sure to consider how you will synchronize things so threads trying to read the data won't collide when the worker thread is reloading the object on file changes.
Upvotes: 0
Reputation: 5134
You can use the setProperty(String key, String value) to change the values at runtime.
py.setProperty("msg", "newValue");
Upvotes: 2