Java Examples: Load and Save Java Application Properties to a Text File - Owlcation - Education
Updated date:

Java Examples: Load and Save Java Application Properties to a Text File

Author:

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 years. I like video games and reading books.

1. Introduction to Java.Util.Properties Class

Most of the enterprise applications settings are actually loaded during the application startup itself and the application behavior is controlled by the application settings persisted in a Flat file or Registry or Database etc.

In this example, we are going to create application property file called "MyApp.Properties" and going store the application settings into that file. We will also read the persisted properties from that file and display that in the Console Window.

2. Key&Value Pairs of Properties

The "Properties Class" of Java is used to maintain one or more properties that can be easily streamed into Text or Binary. Each property is a Key & Value pair. Now, let us create three Property Values and store that in a Java's Properties object called AppProps. This example requires set of Java Packages and the code given below shows those imports:

//Sample 01: Package inclusion
import java.io.IOException;
import java.nio.file.Files;
import java.util.Properties;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.Writer;
import java.io.Reader;

Now look at the screenshot below:

Adding Java Property to Properties Instance

Adding Java Property to Properties Instance

Here, first, we are creating a Java Properties object called AppProps which will hold application properties (Marked as 1). Once the object is on hand, we are storing three properties by calling its "setProperty()" method.

The "setProperties()" method accepts two strings and forms Key-Value Pair. Later, the Value can be retrieved by providing the corresponding Key.

The two parameters passed to it is "Key and Value" pair. For example, the third property we are adding is "FontSize" and the Size of the font is 12. Here, "FontSize" is the Key (Marked as 2) which is passed as First Parameter and 12 is the value for it which is passed as second parameter (Marked as 3). So, in the code snippet, we created three application settings and stored that in a Properties object called AppProps.

Listing 1: Creating Application Settings

//Example 01: Create List of Property Values
Properties AppProps = new Properties();
AppProps.setProperty("Backcolor", "White");
AppProps.setProperty("Forecolor", "Blue");
AppProps.setProperty("FontSize", "12");

The “store()” method of the Java’s Properties Class Persists Key-Value pair to Disc and the “load()” method will read the persisted information from the disc and forms the Key-Value Pair

3. Storing Application Properties Using "Properties::store()" Method

The application properties contained in the Properties Class instance can be persisted to a text file. The “store()” method of the Properties Class is used to save the application properties to a text file. This method takes an OutputStream or Writer object to store the information. Since it accepts OutputStream as well as Writer, in place of a text file, one can write the properties in a binary file as well. The most preferred way is writing it to a text file and preferred extension for the property file is “.properties”. We can persist the information in an XML file also.

Now have a look at the Screenshot below:

Persisting Properties to Text File using Store() method

Persisting Properties to Text File using Store() method

First, we are getting Path to our “.properties file” by making use of the “static get() method” call of the Paths Utility Class (Marked as 1). A Write object PropWriter is then created by calling another utility function “newBufferedWriter()”. This function takes Path to our properties file (Marked as 2).

Now, we have our Writer object and Path object are ready. We are making calls to the Store() method of the Properties class by supplying the Writer object to it (Passed as the first parameter, marked as 3). We are also passing the comment text “Application Properties” as the second parameter (Marked as 4) and this text appears as comment text in the output file.

Once the properties are written to the text file, the content looks as shown below:

Content of MyApp Properties File

Content of MyApp Properties File

The comment passed to the store method appears as the first line in the properties file (Marked as 1) and there are date and time stamp (marked as 2) those tell when the properties are persisted. As these two lines are comment lines, we can see # is prefixed. The actual properties are persisted as “Key & Value” pairs which are marked as 3 in the above screenshot. Note that the default format of a single property is “Key=Value”.

We can also hand-code and create the properties file. Follow the below guidelines:

  1. Key and Value pairs can be created one per line.
  2. Use the “=” or “:” as a separator between Key & Value.
  3. To have = or: in key and/or value, use the escape char \.
  4. To place comment, prefix the line with # or ! symbol.
  5. To organize a group of properties use comment heading and a blank line at the end of the group.

Listing 2: Writing the Properties to Text File

//Example 02: Store Properties to MyApp.Properties
Path PropertyFile = Paths.get("MyApp.Properties");
try
{
	Writer PropWriter = 
			Files.newBufferedWriter(PropertyFile);
	AppProps.store(PropWriter,
			"Application Properties");
	PropWriter.close();
}
catch(IOException Ex)
{
	System.out.println("IO Exception :" +
	Ex.getMessage());
}

4. Loading Properties from Text File Using "Properties::load()" Method

We used "Writer Text Stream" for storing the Application settings in the properties file. Now, we are going to use "Reader Stream" to read the Property settings from the file. Once the properties are read from the “.Properties” to Java’s “Properties Class” instance, we will display the property settings in the Console Output Window. Below is the code snippet for this:

Reading Java Properties From Text File

Reading Java Properties From Text File

First, we are creating the "Reader" instance PropReader by making use of the "newBufferedReader()" method (Marked as 1). Note that we are reusing the PropertyFile instance which we used for writing the application properties. Most of the Time, the property files are created manually and we can use this same approach to read the file.

We are using the “load() method” of the Properties Class to load the Properties stored in the MyApp.Properties file through the passed-in Reader object called PropReader (Marked as 2). After "load()" call, we have the all the property settings loaded into Properties Class instance called AppProps.

The "getProperty()" method of Properties Class takes the Key and returns the Value associated to that Key. In our example, we are calling this method three times and printing the returned result in the Console Output Window (Marked as 3 – 6). Below is the Complete code Example and Its Output.

Reading and Writing Java Property File - Complete Code Example

//Sample 01: Package inclusion
import java.io.IOException;
import java.nio.file.Files;
import java.util.Properties;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.Writer;
import java.io.Reader;

public class Main
{
    public static void main(String[] args)
    {
        //Example 01: Create List of Property Values
        Properties AppProps = new Properties();
        AppProps.setProperty("Backcolor", "White");
        AppProps.setProperty("Forecolor", "Blue");
        AppProps.setProperty("FontSize", "12");

        //Example 02: Store Properties to MyApp.Properties
        Path PropertyFile = Paths.get("MyApp.Properties");
        try
        {
            Writer PropWriter = 
                    Files.newBufferedWriter(PropertyFile);
            AppProps.store(PropWriter,
                    "Application Properties");
            PropWriter.close();
        }
        catch(IOException Ex)
        {
            System.out.println("IO Exception :" +
            Ex.getMessage());
        }

        //Example 03: Load Properties from MyApp.Properties
        try
        {
            //3.1 Load properties from File to Property
            // object
            Reader PropReader = 
                    Files.newBufferedReader(PropertyFile);
            AppProps.load(PropReader);

            //3.2 Read Property and Display it in Console
            System.out.println("Application BackColor:" +
                    AppProps.getProperty("Backcolor"));
            System.out.println("Application ForeColor:" +
                    AppProps.getProperty("Forecolor"));
            System.out.println("Application Font Size:" +
                    AppProps.getProperty("FontSize"));

            //3.3 Close the Reader File
            PropReader.close();
        }
        catch(IOException Ex)
        {
            System.out.println("IO Exception :" +
                    Ex.getMessage());
        }
    }
}

Output of the Code Example

Output of the Code Example

Output of the Code Example

5. Conclusion

The Java Programmers usually pick ".Properties" as file extension which persists the Java Properties to a Text file. We saw the usage of the store() and load() methods of the Java's "Properties Class" and how it stores and retrieves the application properties from the ".properties" file. Since the Java ".Properties" files are usually ASCII Standard text files we used Java's Reader and Writer objects.

In this example, we saw Properties persisted as a text file. The Java's Properties class supports storing and retrieving the data from XML File as well through APIs "loadFromXml()" and "storeToXML()".