In this tutorial I will show you how to store and retrieve values from a properties file in Java
There are a number of scenarios where you may want to have a configuration file for your Java program. Java has a build in mechanisms in java.util.Properties allowing you to easily access and change the values in a configuration file.
Properties are constructed by a key and a value pair, both represented as String objects. You may think of properties as a persistent Hashtable.
Write Data to Properties File
Properties properties = new Properties();
properties.setProperty("server_name", "javatutorial.net");
properties.setProperty("request_timeout", "5000");
OutputStream output = new FileOutputStream("config.properties");
properties.store(output, null);
Read Data from Properties File
InputStream input = new FileInputStream("config.properties");
Properties properties = new Properties();
properties.load(input);
String serverNamere = properties.getProperty("server_name");
In this example I didn’t included the exception handling for more visibility. Do not forget to add a proper exception handling in your programs and to close the file input and output streams when you are done with reading/writing the properties.


