How to Create and Store Property File Dynamically in Java


In this example we will show how to create and store property file dynamically. To write the contents of properties to a file, you first obtain an output stream, and then use the Store() method in the properties object to complete saving the contents of properties to the file.

Source Code

package com.beginner.examples;


import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

public class StorePropertiesExample {

	public static void main(String[] args) {

		// Create a Properties collection
		Properties colorPro = new Properties();

		//Add something to this collection
		colorPro.setProperty("color_1", "red");
		colorPro.setProperty("color_2", "yellow");
		colorPro.setProperty("color_3", "blue");
		colorPro.setProperty("color_4", "black");
		colorPro.setProperty("color_5", "white");
		
		//Writes the contents of the collection to a file
		//The first step is to get a character output stream (or byte stream)
		FileWriter writer = null;
		
		try {
			writer = new FileWriter("colorPro.txt");
			
			//Use the store() method in the Properties object to do this
			colorPro.store(writer, null);
			
			//Close the resource
			writer.close();
			
			System.out.println("Done");
			
		}catch(IOException e) {
			
			e.printStackTrace();
		}
		
	}

}

Output:

Done

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments