Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving properties in a file with JAVA formatted

Is there a way to save Properties in Java with some formatting using the Properties object? Like is there a way to introduce new lines between entries? Or comments before each key?

I know this can be easilly done with normal I/O but wondered if there's a way of doing it with the properties object.

like image 964
javydreamercsw Avatar asked Apr 08 '11 18:04

javydreamercsw


1 Answers

The key to writing a comment between each set of properties is to store them in multiple Properties objects.

ie

FileOutputStream fos = new FileOutputStream("c:/myconfig.property");
Properties prop = new Properties();
prop.put("com.app.port", "8080");
prop.put("com.app.ip", "127.0.0.1");

prop.store(fos, "A Test to write properties");
fos.flush();

Properties prop2 = new Properties();
prop2.put("com.app.another", "Hello World");
prop2.store(fos, "Where does this go?");
fos.flush();

fos.close();

This will produce an output such as

#A Test to write properties
#Fri Apr 08 15:28:26 ADT 2011
com.app.ip=127.0.0.1
com.app.port=8080
#Where does this go?
#Fri Apr 08 15:28:26 ADT 2011
com.app.another=Hello World
like image 80
Sean Avatar answered Sep 20 '22 23:09

Sean