Properties file in Java

Property files are most simple form of data storage. They contain parameters organized as key=value format. They are usually used as initialization files for applications and contain parameters for an application to startup successfully. Properties files are plain text files so they can be easily modified.

In the following example we will read properties file from Java application, modify properties and store them back to file. At the end we will read file again to see if data is really modified.

My properties file looks like this (test.properties). It contains two parameters name and language:

#Sat Jun 18 11:40:00 CEST 2011
name=John
language=English

Once we loaded Properties through the FileInputStream class, they can be easily accessed through getProperty(key) method. In the same way properties can be modified with setProperty(key, value) method and stored back to file. This is what we do in the following code.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesTest {

public static Properties props;

public static void main(String[] args) {

readPropertiesFile();
modifyProperties();
writePropertiesFile();
readPropertiesFile();

}

public static void readPropertiesFile() {

System.out.println("=== read file");

props = new Properties();

try {

props.load(new FileInputStream("path/to/your/test.properties"));

String name = props.getProperty("name");
String language = props.getProperty("language");

System.out.println(name);
System.out.println(language);

}

catch (IOException e) {
e.printStackTrace();
}
}

public static void modifyProperties() {

System.out.println("=== modify properties");
String name = props.getProperty("name");
if (name.equals("John")) {
name = "Helmut";
} else {
name = "John";
}
props.setProperty("name", name);

String language = props.getProperty("language");
if (language.equals("English")) {
language = "German";
} else {
language = "English";
}
props.setProperty("language", language);
}


public static void writePropertiesFile() {
System.out.println("=== write to file");
try {
props.store(new FileOutputStream("path/to/your/test.properties"), "This is optional comment");
} catch (IOException e) {
}
}

}

Run the code (you might set correct path to the file) and check test.properties file again. It should contain something like this:

#Sat Jun 18 11:41:11 CEST 2011
name=Helmut
language=German