Basically, I have to overwrite a certain property in a .properties file through a Java app, but when I use Properties.setProperty() and Properties.Store() it overwrites the
public class PropertiesXMLExample {
public static void main(String[] args) throws IOException {
// get properties object
Properties props = new Properties();
// get path of the file that you want
String filepath = System.getProperty("user.home")
+ System.getProperty("file.separator") +"email-configuration.xml";
// get file object
File file = new File(filepath);
// check whether the file exists
if (file.exists()) {
// get inpustream of the file
InputStream is = new FileInputStream(filepath);
// load the xml file into properties format
props.loadFromXML(is);
// store all the property keys in a set
Set names = props.stringPropertyNames();
// iterate over all the property names
for (Iterator i = names.iterator(); i.hasNext();) {
// store each propertyname that you get
String propname = i.next();
// set all the properties (since these properties are not automatically stored when you update the file). All these properties will be rewritten. You also set some new value for the property names that you read
props.setProperty(propname, props.getProperty(propname));
}
// add some new properties to the props object
props.setProperty("email.support", "donot-spam-me@nospam.com");
props.setProperty("email.support_2", "donot-spam-me@nospam.com");
// get outputstream object to for storing the properties into the same xml file that you read
OutputStream os = new FileOutputStream(
System.getProperty("user.home")
+ "/email-configuration.xml");
// store the properties detail into a pre-defined XML file
props.storeToXML(os, "Support Email", "UTF-8");
// an earlier stored property
String email = props.getProperty("email.support_1");
System.out.println(email);
}
}
}
The output of the program would be:
support@stackoverflow.com