Java Write to properties file


 

Java Write to properties file

In this section, you will learn how to write data to properties file.

In this section, you will learn how to write data to properties file.

Java Write to properties file

In this section, you will learn how to write data to properties file.

 The properties file is basically used to store the configuration data or settings.It stores the data in key-value pair. Java has provide Properties class to store data into .properties file. It consists of a hashtable data structure of String keys with a String value for each key. Here we are going to create a .properties file and write data to it in the form of key-value.

In the given example, we have created an object of Properties class and put three key/value pairs within the Properties object using the setProperty() method.  The store method of the Properties class is then store the Properties object to the file.

Example:

import java.io.*;
import java.util.*;

public class WritePropertiesFile {
	public static void main(String[] args) {
		try {
			Properties properties = new Properties();
			properties.setProperty("Natinal-Animal", "Tiger");
			properties.setProperty("Natinal-Flower", "Lotus");
			properties.setProperty("National-Bird", "Peacock");

			File file = new File("file.properties");
			FileOutputStream fos = new FileOutputStream(file);
			properties.store(fos, "");
			fos.close();
		} catch (FileNotFoundException e){
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Output:

#Wed Sep 26 16:56:26 IST 2012
Natinal-Flower=Lotus
National-Bird=Peacock
Natinal-Animal=Tiger

Ads