Ankit_Add

Wednesday, January 14, 2015

Properties File in Java

Java Properties file are a very important concept

Basically, Java properties file is used to store project configuration data or settings.

Properties are configuration values managed as key/value pairs. In each pair, the key and value are both String values.The use of Key is to retrieve the value that is saved in configuration file

Lets take an example to understand the concept of configuration file. How these file can be created an how to save and retrieve the values in this file

1. Create a configuration file and Save the configuration in it

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class WriteProperties {
   
    public static void main(String[] args) {
       
        Properties prop = new Properties();
        OutputStream output = null;
   
        try {
           //Create a configuration file on specific path
            output = new FileOutputStream("G:\\config.properties");
   
            // set the properties value in file
            prop.setProperty("Country", "India");
            prop.setProperty("City", "Delhi");
            prop.setProperty("Place", "IndiaGate");
   
            // save properties in file
            prop.store(output, null);
              
        } catch (IOException io) {
            io.printStackTrace();
        }

    }

}

OutPut: After running this program a file config.properties has been created in the specified path with following data
#Wed Jan 14 00:33:17 IST 2015
Country=India
City=Delhi
Place=IndiaGate




2. Load a properties file in system and retrieve the data from the file

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

public class ReadProperties {
  public static void main(String[] args) {

    Properties prop = new Properties();
    InputStream input = null;

    try {

        input = new FileInputStream("G:\\config.properties");

        // load a properties file in system
        prop.load(input);

        System.out.println(prop.getProperty("Coutry"));
        System.out.println(prop.getProperty("City"));
        System.out.println(prop.getProperty("Place"));

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

OutPut : After running this program the properties file will be loaded in system and it will use all the setting written in the file

No comments:

Post a Comment