Reputation: 3762
The following code doesn't appear to work, and yet I'm sure it used to.
public static void main(String args[])
{
Properties currentProperties = System.getProperties();
Properties p = new Properties(currentProperties);
System.setProperties(p);
}
During the construction of the new Properties object the old properties are not added, so when System.setProperties is called it has the effect of wiping all of the system properties.
What's also odd is there is an example of code similar to this on the Oracle website.
https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
Could someone please explain why this code doesn't work? And what one should do in place of this code?
I am using Java 1.7_75 64-0-bit.
Thanks Rich
Upvotes: 2
Views: 1351
Reputation: 28136
Take a look at Java docs. The constuctor
public Properties(Properties defaults)
as mentioned
Creates an empty property list with the specified defaults.
creates a new Properties instance, but doesn't initialize it with properties from the input parameter, it only sets default values for this new instance.
Upvotes: 4
Reputation: 286
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class App {
public static void main(String[] args) {
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("config.properties");
// set the properties value
prop.setProperty("database", "localhost");
prop.setProperty("dbuser", "user");
prop.setProperty("dbpassword", "password");
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
As far as I am concerned this is the only way to create and save properties.
Upvotes: 0