Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

Getting Started with Java Properties

$
0
0

The Master Class of "Learn Spring Security" is live:

>> CHECK OUT THE COURSE

1. Overview

Most Java application need to use properties at some point, generally to store simple parameters as key-value pairs, outside of compiled code.

And so the language has first class support for properties – the java.util.Properties – an utility class designed for handling this type of configuration files.

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

2. Loading Properties

2.1. From Properties Files

Let’s start with an example for loading key-value pairs from properties files; we’re loading 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 the properties files are recommended to use “.properties“, the suffix, 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));

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

2.2. Load From XML Files

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

Here is 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));

3. Get Properties

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

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

Example code:

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

Note that although Properties class inherits get() method from Hashtable class, I wouldn’t recommend you use it to get value. Because its 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 you.

The code below will throw an Exception:

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

4. Set Properties

We can use setProperty() method to update an existed key-value pair or add a new key-value pair.

Example code:

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");
String newAppDownloadAddr = appProps.getProperty("downloadAddr");
System.out.println("new app name: " + newAppName);
System.out.println("new app downloadAddr: " + newAppDownloadAddr);

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

The code below will not work as you wish, when you use getProperty() to get its value, it will return null:

appProps.put("version", 2);

5. Remove Properties

If you want to remove a key-value pair, you can use remove() method.

Example Code:

System.out.println("before removal, version is: " + appProps.getProperty("version"));
appProps.remove("version");
System.out.println("after removal, version is: " + appProps.getProperty("version"));

6. Store

6.1. Store to Properties Files

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

Example code:

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

The second parameter is for comment. If you don’t want to write any comment, simply use null for it.

6.2. Store to XML Files

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

Example code:

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

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

7. Other Common Operations

Properties class also provides some other methods to operate the properties.

Example code:

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();
System.out.println(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 is not 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));

System.out.println(appProps.getProperty("name"));
System.out.println(appProps.getProperty("version"));
System.out.println(appProps.getProperty("site"));

7. 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 that 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 – we can specify the encoding in a third parameter of the  storeToXML() API.

8. Conclusion

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

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

I just released the Master Class of "Learn Spring Security" Course:

>> CHECK OUT THE COURSE


Viewing all articles
Browse latest Browse all 4535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>