How do I convert ResourceBundle to Properties?

package org.kodejava.util;

import java.util.*;

public class ResourceBundleToProperties {
    public static void main(String[] args) {
        // Load resource bundle Messages_en_GB.properties from the classpath.
        ResourceBundle resource = ResourceBundle.getBundle("Messages", Locale.UK);

        // Call the convertResourceBundleToProperties method to convert the resource
        // bundle into a Properties object.
        Properties properties = convertResourceBundleToProperties(resource);

        // Print the entire contents of the Properties.
        Enumeration<Object> keys = properties.keys();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            String value = (String) properties.get(key);
            System.out.println(key + " = " + value);
        }
    }

    /**
     * Convert ResourceBundle into a Properties object.
     *
     * @param resource a resource bundle to convert.
     * @return Properties a properties version of the resource bundle.
     */
    private static Properties convertResourceBundleToProperties(ResourceBundle resource) {
        Properties properties = new Properties();
        Enumeration<String> keys = resource.getKeys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            properties.put(key, resource.getString(key));
        }
        return properties;
    }
}

How do I store properties as XML file?

In the previous example, How do I load properties from XML file? we read properties from XML file. Now it’s the turn on how to store the properties as XML file.

package org.kodejava.io;

import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

public class PropertiesToXml {
    public static void main(String[] args) throws Exception {
        Properties properties = new Properties();
        properties.setProperty("db.type", "mysql");
        properties.setProperty("db.url", "jdbc:mysql://localhost:3306/kodejava");
        properties.setProperty("db.username", "root");
        properties.setProperty("db.password", "");

        FileOutputStream fos = new FileOutputStream("db-config.xml");
        properties.storeToXML(fos, "Database Configuration", StandardCharsets.UTF_8);
    }
}

The saved XML file will look like the properties file below:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <comment>Database Configuration</comment>
    <entry key="db.type">mysql</entry>
    <entry key="db.password"></entry>
    <entry key="db.username">root</entry>
    <entry key="db.url">jdbc:mysql://localhost:3306/kodejava</entry>
</properties>

How do I load properties from XML file?

Reading XML properties can be easily done using the java.util.Properties.loadFromXML() method. Just like reading the properties from a file that contains a key=value pairs, the XML file will also contain a key and value wrapped in the following XML format.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <comment>Application Configuration</comment>
    <entry key="data.folder">D:\AppData</entry>
    <entry key="jdbc.url">jdbc:mysql://localhost/kodejava</entry>
</properties>
package org.kodejava.util;

import java.util.Properties;

public class LoadXmlProperties {
    public static void main(String[] args) {
        LoadXmlProperties demo = new LoadXmlProperties();
        try {
            Properties properties = demo.readProperties();

            //Display all properties information
            properties.list(System.out);

            // Read the value of data.folder and jdbc.url configuration
            String dataFolder = properties.getProperty("data.folder");
            System.out.println("data.folder = " + dataFolder);
            String jdbcUrl = properties.getProperty("jdbc.url");
            System.out.println("jdbc.url    = " + jdbcUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Properties readProperties() throws Exception {
        Properties properties = new Properties();
        properties.loadFromXML(getClass().getResourceAsStream("/configuration.xml"));
        return properties;
    }
}

The result of the code snippet above:

-- listing properties --
data.folder=D:\AppData
jdbc.url=jdbc:mysql://localhost/kodejava
data.folder = D:\AppData
jdbc.url    = jdbc:mysql://localhost/kodejava

How do I get path / classpath separator?

OS platform has a different symbol used for path separator. Path separator is a symbol that separate one path element from the other. In Windows the path separator is a semicolon symbol (;), you have something like:

.;something.jar;D:/libs/commons.jar

While in Linux based operating systems the path separator is a colon symbol (:), it looks like:

.:something.jar:/libs/commons.jar

To obtain the path separator you can use the following code.

package org.kodejava.lang;

import java.util.Properties;

public class PathSeparator {
    public static void main(String[] args) {
        // Get System properties
        Properties properties = System.getProperties();

        // Get the path separator which is unfortunately
        // using a different symbol in different OS platform.
        String pathSeparator = properties.getProperty("path.separator");
        System.out.println("pathSeparator = " + pathSeparator);
    }
}

How do I read a configuration file using java.util.Properties?

When we have an application that used a text file to store a configuration, and the configuration is typically in a key=value format then we can use java.util.Properties to read that configuration file.

Here is an example of a configuration file called app.config:

app.name=Properties Sample Code
app.version=1.0

The code below show you how to read the configuration.

package org.kodejava.util;

import java.io.*;
import java.net.URL;
import java.util.Objects;
import java.util.Properties;

public class PropertiesExample {
    public static void main(String[] args) {
        Properties prop = new Properties();
        try {
            // the configuration file name
            String fileName = "app.config";
            ClassLoader classLoader = PropertiesExample.class.getClassLoader();

            // Make sure that the configuration file exists
            URL res = Objects.requireNonNull(classLoader.getResource(fileName),
                "Can't find configuration file app.config");

            InputStream is = new FileInputStream(res.getFile());

            // load the properties file
            prop.load(is);

            // get the value for app.name key
            System.out.println(prop.getProperty("app.name"));
            // get the value for app.version key
            System.out.println(prop.getProperty("app.version"));

            // get the value for app.vendor key and if the
            // key is not available return Kode Java as
            // the default value
            System.out.println(prop.getProperty("app.vendor","Kode Java"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The code snippet will print these results:

Properties Sample Code
1.0
Kode Java