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

Updated on May 23, 2018
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 Yrs. I like playing video games & 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 | Source

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 | Source

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 | Source

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 | Source

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 | Source

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()".


Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://owlcation.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)