Problem:
How to store Java Properties? Properties class has methods to store/save to different outputs – OutputStream, Writer or even XML file. Here’s an example of Properties.store(OutputStream).
Solution:
java.util.Properties class has a few methods that allow to save properties (key-value pairs) in a format suitable for further load using Properties.load() methods. The methods to save properties are:
- void save(OutputStream out, String comments)
This one is Deprecated. so we won’t describe it – use below methods instead. - void store(OutputStream out, String comments)
Writes property list into OutputStream and precedes with comments (see below example and it become clear ;-) ) - void store(Writer writer, String comments)
Writes property list into Writer and precedes with comments (as the above method, but using Writer).
Here’s an example of Properties.store(OutputStream) in action:
package com.farenda.java.util; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.Properties; public class PropertiesStore { public static void main(String[] args) throws IOException { Properties config = createAppProperties(); printToSystemOutput(config); Path configFile = saveToFile(config); displayFile(configFile); } private static Properties createAppProperties() { Properties config = new Properties(); config.setProperty("minThreads", "5"); config.setProperty("maxThreads", "40"); return config; } private static void displayFile(Path path) throws IOException { System.out.printf("%nContents of %s:%n", path.toString()); Files.readAllLines(path).forEach(System.out::println); } private static void printToSystemOutput(Properties config) throws IOException { config.store(System.out, "Writing to System.out:"); } private static Path saveToFile(Properties config) throws IOException { Path file = Files.createTempFile("app-config", ".properties"); // To use store(Writer) change to Files.newBufferedWriter(file) try (OutputStream stream = Files.newOutputStream(file)) { config.store(stream, "Writing to a file using OutputStream:"); } return file; } }
In the example we’ve used a few features from Java 7 and Java 8 – java.Path, Files, try-with-resources, and forEach to which we pass static method as parameter.
And here is the result of running the above code:
#Writing to System.out: #Sat Sep 05 10:25:24 CEST 2015 maxThreads=40 minThreads=5 Contents of /tmp/app-config8047556758778700402.properties: #Writing to a file using OutputStream: #Sat Sep 05 10:25:24 CEST 2015 maxThreads=40 minThreads=5
Note that the properties have not been written in the same order they were added into the Properties object. Another thing is that the timestamp is added automatically – at wasn’t in the comments.