Course – LS – All
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

Most Java applications need to use properties at some point, generally to store simple parameters as key-value pairs outside of compiled code. As such, the language has first class support for properties with java.util.Properties, a utility class designed for handling these types of configuration files.

That’s what we’ll focus on in this tutorial.

2. Loading Properties

2.1. From Properties Files

Let’s start with an example for loading key-value pairs from properties files. We’ll load two files we have available on our classpath:

app.properties:

version=1.0
name=TestApp
date=2016-11-12

And catalog:

c1=files
c2=images
c3=videos

Notice that although it’s recommended for the properties files to use the suffix “.properties“, it’s not necessary.

We can now load them very simply into a Properties instance:

String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
String catalogConfigPath = rootPath + "catalog";

Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));

Properties catalogProps = new Properties();
catalogProps.load(new FileInputStream(catalogConfigPath));

  
String appVersion = appProps.getProperty("version");
assertEquals("1.0", appVersion);
        
assertEquals("files", catalogProps.getProperty("c1"));

As long as a file’s contents meet the properties file format requirements, it can be parsed correctly by the Properties class. Here are more details for Property file format.

2.2. Load From XML Files

Besides properties files, the Properties class can also load XML files, which conform to the specific DTD specifications.

Here’s an example for loading key-value pairs from an XML file, icons.xml:

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <comment>xml example</comment>
    <entry key="fileIcon">icon1.jpg</entry>
    <entry key="imageIcon">icon2.jpg</entry>
    <entry key="videoIcon">icon3.jpg</entry>
</properties>

Now let’s load it:

String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String iconConfigPath = rootPath + "icons.xml";
Properties iconProps = new Properties();
iconProps.loadFromXML(new FileInputStream(iconConfigPath));

assertEquals("icon1.jpg", iconProps.getProperty("fileIcon"));

3. Get Properties

We can use getProperty(String key) and getProperty(String key, String defaultValue) to get the value by its key.

If the key-value pair exists, the two methods will both return the corresponding value. But if there’s no such key-value pair, the former will return null, and the latter will return defaultValue instead:

String appVersion = appProps.getProperty("version");
String appName = appProps.getProperty("name", "defaultName");
String appGroup = appProps.getProperty("group", "baeldung");
String appDownloadAddr = appProps.getProperty("downloadAddr");

assertEquals("1.0", appVersion);
assertEquals("TestApp", appName);
assertEquals("baeldung", appGroup);
assertNull(appDownloadAddr);

Note that although the Properties class inherits the get() method from the Hashtable class, we wouldn’t recommend using it to get the value. The get() method will return an Object value, which can only be cast to String, and the getProperty() method already handles the raw Object value properly for us.

The code below will throw an Exception:

float appVerFloat = (float) appProps.get("version");

4. Set Properties

We can use the setProperty() method to update an existing key-value pair or add a new key-value pair:

appProps.setProperty("name", "NewAppName"); // update an old value
appProps.setProperty("downloadAddr", "www.baeldung.com/downloads"); // add new key-value pair

String newAppName = appProps.getProperty("name");
assertEquals("NewAppName", newAppName);
        
String newAppDownloadAddr = appProps.getProperty("downloadAddr");
assertEquals("www.baeldung.com/downloads", newAppDownloadAddr);

Note that although the Properties class inherits the put() and putAll() methods from the Hashtable class, we wouldn’t recommend using them for the same reason as the get() method; only String values can be used in Properties.

The code below won’t work as desired; when we use getProperty() to get its value, it’ll return null:

appProps.put("version", 2);

5. Remove Properties

If we want to remove a key-value pair, we can use the remove() method;

String versionBeforeRemoval = appProps.getProperty("version");
assertEquals("1.0", versionBeforeRemoval);

appProps.remove("version");    
String versionAfterRemoval = appProps.getProperty("version");
assertNull(versionAfterRemoval);

6. Store

6.1. Store to Properties Files

The Properties class provides a store() method to output key-value pairs:

String newAppConfigPropertiesFile = rootPath + "newApp.properties";
appProps.store(new FileWriter(newAppConfigPropertiesFile), "store to properties file");

The second parameter is for comments. If we don’t want to write any comments, we can simply use null for it.

6.2. Store to XML Files

The Properties class also provides a storeToXML() method to output key-value pairs in XML format:

String newAppConfigXmlFile = rootPath + "newApp.xml";
appProps.storeToXML(new FileOutputStream(newAppConfigXmlFile), "store to xml file");

The second parameter is the same as in the store() method.

7. Other Common Operations

The Properties class also provides some other methods to operate the properties:

appProps.list(System.out); // list all key-value pairs

Enumeration<Object> valueEnumeration = appProps.elements();
while (valueEnumeration.hasMoreElements()) {
    System.out.println(valueEnumeration.nextElement());
}

Enumeration<Object> keyEnumeration = appProps.keys();
while (keyEnumeration.hasMoreElements()) {
    System.out.println(keyEnumeration.nextElement());
}

int size = appProps.size();
assertEquals(3, size);

8. Default Property List

A Properties object can contain another Properties object as its default property list. The default property list will be searched if the property key isn’t found in the original one.

Besides “app.properties,” we have another file, “default.properties,” on our classpath:

default.properties:

site=www.google.com
name=DefaultAppName
topic=Properties
category=core-java

Example Code:

String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();

String defaultConfigPath = rootPath + "default.properties";
Properties defaultProps = new Properties();
defaultProps.load(new FileInputStream(defaultConfigPath));

String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties(defaultProps);
appProps.load(new FileInputStream(appConfigPath));

assertEquals("1.0", appVersion);
assertEquals("TestApp", appName);
assertEquals("www.google.com", defaultSite);

9. Properties and Encoding

By default, properties files are expected to be ISO-8859-1 (Latin-1) encoded, so properties with characters outside of the ISO-8859-1 shouldn’t generally be used.

We can work around this limitation with the help of tools, such as the JDK native2ascii tool or explicit encodings on files, if necessary.

For XML files, the loadFromXML() method and the storeToXML() method use UTF-8 character encoding by default.

However, when reading an XML file encoded differently, we can specify that in the DOCTYPE declaration. Writing is also flexible enough, and we can specify the encoding in a third parameter of the storeToXML() API.

10. Conclusion

In this article, we discussed basic Properties class usage. We learned how to use Properties; load and store key-value pairs in both properties and XML format; operate key-value pairs in a Properties object, such as retrieve values, update values, and get its size; and finally, how to use a default list for a Properties object.

The complete source code for the example is available in this GitHub project.

Course – LS – All
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.