Properties file are often used in Java applications in the aim to store configuration parameters, internationalization and various informations. Each line of a properties file is a key/value entry. The key and the value are separated by the equal symbol « = ». In this tutorial, we will see how to write properties file in Java.
1 – Write properties file
Java offers the Properties class from the java.util package to read properties file. Below an example :We will write a properties file named config.properties
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 |
package com.roufid.properties; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.Properties; /** * @author Radouane ROUFID. * */ public class WritePropertiesExample { public static void main(String[] args) { // Properties file path. String filePath = "c:/files/config.properties"; Properties prop = new Properties(); try (Writer inputStream = new FileWriter(filePath)) { // Setting the properties. prop.setProperty("database.url", "localhost"); prop.setProperty("database.login", "roufid"); prop.setProperty("database.password", "password"); // Storing the properties in the file with a heading comment. prop.store(inputStream, "Database information"); } catch (IOException ex) { System.out.println("Problem occurs when reading file !"); ex.printStackTrace(); } } } |
Config.properties content :
1 2 3 4 5 |
#Database information #Wed Mar 09 14:50:19 CET 2016 database.password=password database.login=roufid database.url=localhost |
Note that use can store your properties in a XML file by using
1 |
prop.storeToXML(inputStream, "Database information"); |
instead of
1 |
prop.store(inputStream, "Database information"); |