How to write to properties file in Java


One of most visited posts on this blog is How to read properties file in Java. In that post I explained how you can read from a properties file. But many people came to that post searching for an example on how to write to a properties file. So I thought it will be beneficial for those visitors if we a have separate post with an example of how to write to a properties file in Java.

import java.util.*;
import java.io.*;
class WriteToPropertiesFile
{
    PrintWriter output = null;
    public  void writeToFile(HashMap map,String fileName) throws Exception{
	    Properties properties = new Properties();
		Set set = map.keySet();
	    Iterator itr = set.iterator();
  		while(itr.hasNext()){
		    String key = (String)itr.next();
			String value = map.get(key);
            properties.setProperty(key, value);
        }

		//We have all the properties, now write them to the file.
		//The second argument is optional. You can use it to identify the file.
		properties.store(new FileOutputStream(fileName),"Java properties test");

		//To keep this example simple, I did not include any exception handling
		//code, but in your application you might want to handle exceptions here
		//according to your requirements.

	}
 }


This method takes a HashMap of keys and values and the name of the properties file to be created as the input parameters. The idea behind using the hash map is to make this method generic. You can get your properties from an input file, command line arguments or any where else. But once you have those values you can put them in a HashMap and call this method to write those properties to a file.

Here is simple method that demonstrates how you can call the above method to write values to a properties file.

public static void main(String args[]) throws Exception{
		WriteToPropertiesFile wtp = new WriteToPropertiesFile();
		HashMap map = new HashMap();
		map.put("lang","java");
		map.put("OS","Windows");
		map.put("version","1.6");
		wtp.writeToFile(map,"C://temp//test//sample.properties");
	}

Here is the output.

#Java properties test
#Mon Nov 09 12:41:34 CST 2009
version=1.6
OS=Windows
lang=java

Good Luck!