Skip to content

Instantly share code, notes, and snippets.

@jmorenoamor
Created June 7, 2012 15:36
Show Gist options
  • Save jmorenoamor/2889489 to your computer and use it in GitHub Desktop.
Save jmorenoamor/2889489 to your computer and use it in GitHub Desktop.
Properties file reading and writing example with Java
package com.morenoamor.tutorials;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
/**
* Properties file reading and writing example
*
* @author Jesús Moreno Amor <[email protected]>
*/
public class PropertiesFile
{
public static void main(String[] args)
{
String properties_file_path = "/path/to/file/properties_file.properties";
FileInputStream input_stream = null;
FileOutputStream output_stream = null;
try
{
Properties properties = new Properties();
// Loading from INI format
input_stream = new FileInputStream(properties_file_path);
properties.load(input_stream);
input_stream.close();
// Loading from XML fromat
input_stream = new FileInputStream(properties_file_path);
properties.loadFromXML(input_stream);
input_stream.close();
// Gettng value of a property
System.out.println("The value of key_name key is: " + properties.getProperty("key_name"));
// Setting value of a property
properties.setProperty("keyA", "value1");
properties.setProperty("keyB", "value2");
properties.setProperty("keyC", "value3");
// Storing to INI format
output_stream = new FileOutputStream(properties_file_path);
properties.store(output_stream, "Comments");
output_stream.close();
// Storing to XML format
output_stream = new FileOutputStream(properties_file_path);
properties.storeToXML(output_stream, "Comments");
output_stream.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment