Write values to a properties file in Java
This post will discuss how to write values to a properties file in Java.
1. In Plain Java
A properties file consists of key-value pairs of string type. We can write values to a properties file in plain Java using the Properties class.
The preferred way to save a properties list is to load the properties file from the classpath or file system into a Properties object and set the given property list (key and element pairs) in that object using its setProperty(…) method. Then we write the properties from this Properties object back to the properties file by passing a FileOutputStream via the store(OutputStream out, String comments) method of the Properties class. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import java.io.*; import java.util.Properties; class Main { public static void main(String[] args) { File file = new File("/var/www/html/config.properties"); Properties prop = new Properties(); try (InputStream in = new FileInputStream(file)) { if (in == null) { throw new FileNotFoundException(); } prop.load(in); prop.setProperty("key", "value"); OutputStream out = new FileOutputStream(file); prop.store(out, "some comment"); } catch (IOException e) { e.printStackTrace(); } printProperties(prop); } public static void printProperties(Properties prop) { prop.stringPropertyNames().stream() .map(key -> key + ":" + prop.getProperty(key)) .forEach(System.out::println); } } |
2. Using Apache Commons Configuration
We can even write values to a properties file in Java using third-party libraries like Apache Commons Configuration. Here’s a working example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; class Main { public static void main(String[] args) { File file = new File("/var/www/html/config.properties"); PropertiesConfiguration config = null; try { config = new PropertiesConfiguration(file); config.setProperty("key", "value"); OutputStream out = new FileOutputStream(file); config.save(out); } catch (ConfigurationException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } System.out.println(config.getString("key")); } } |
That’s all about writing values to a properties file in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)