Thursday, 16 October 2014

Java Properties file

Properties class represents a persistent set of properties. These properties can be saved to a stream or loaded from a stream. Java properties file is used to store project configuration data or settings.

Java Properties class provides below constructors, to instantiate Properties class.

Properties()
Creates an empty property list with no default values.
Properties(Properties defaults)
Creates an empty property list with the specified defaults.

How to write to properties file
Step 1: Instantiate Properties class.
Ex: Properties properties = new Properties();

Step 2: Create properties file
Ex: FileOutputStream out = new FileOutputStream("project.properties");

Step 3: Set properties
Ex: properties.setProperty("width", "120");

Step 4: Store the properties to file.
Ex: properties.store(out, "Project configurations");

Example
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class WriteToPropertyFile {
    public static void main(String args[]) throws FileNotFoundException, IOException{
        Properties properties = new Properties();
        FileOutputStream out = new FileOutputStream("project.properties");

        properties.setProperty("width", "120");
        properties.setProperty("height", "55");
        properties.setProperty("maxicons", "9");

        properties.store(out, "Project configurations");
        
        out.close();
    }
}


When you run above program, “project.properties” file will be created with below content.

project.properties
#Project configurations
#Thu Oct 16 17:35:41 IST 2014
height=55
width=120
maxicons=9

How to read from properties file
Step 1: Instantiate Properties class.
Ex: Properties properties = new Properties();

Step 2: Create FileInputStream instance to read from properties file
Ex: FileInputStream fin = new FileInputStream("project.properties");

Step 3: Load properties file
Ex: properties.load(fin);

Step 4: Read the properties.
Ex: properties.getProperty("height")

Example
import java.io.FileInputStream;
import java.util.Properties;

public class ReadFromPropertyFile {
    public static void main(String args[]) throws Exception{
        Properties properties = new Properties();
        FileInputStream fin = new FileInputStream("project.properties");

        properties.load(fin);

        System.out.println(properties.getProperty("height"));
        System.out.println(properties.getProperty("width"));
        System.out.println(properties.getProperty("maxicons"));

        fin.close();
    }
}

Output
55
120
9

No comments:

Post a Comment