Warning: Use of undefined constant fixed - assumed 'fixed' (this will throw an Error in a future version of PHP) in /home/webtro13/domains/farenda.com/public_html/wp-content/themes/moments/header.php on line 65

Java Programming Tutorials

Java programming tutorials with many code examples!

Java Properties store as XML


How to store Java Properties as XML? It turns out that it’s not only possible, but also easy with the Properties class as you can see in the example in this post.


In post Java Properties store we’ve described how to store Properties as flat text files. In this post we’ll show how to store them as XML, which sometimes is very handy:

package com.farenda.java.util;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;

public class PropertiesStoreXml {

    public static void main(String[] args) throws IOException {
        Properties config = createAppProperties();

        Path configFile = saveAsXml(config);


    private static Properties createAppProperties() {
        Properties config = new Properties();
        config.setProperty("connectionTimeMillis", "1000");
        config.setProperty("databaseURL", "localhost:2097");
        return config;

    private static void displayFile(Path path) throws IOException {
        System.out.printf("%nContents of %s:%n", path.toString());

    private static Path saveAsXml(Properties config) throws IOException {
        Path file = Files.createTempFile("app-config", ".xml");
        try (OutputStream stream = Files.newOutputStream(file)) {
            config.storeToXML(stream, "Application properties as XML");
        return file;

Here we use Files and Path facilities available since Java 7. java.util.Properties class has two methods to store as XML:

  • void storeToXML(OutputStream os, String comment)
    Writes properties to OutputStream as XML with comment as comment element (see output) using UTF-8 encoding.
  • void storeToXML(OutputStream os, String comment, String encoding)
    Writes properties to OutputStream as XML with comment as comment element (see output), using provided encoding.

Running the example gives the following result:

Contents of /tmp/app-config7193299867429345100.xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<comment>Application properties as XML</comment>
<entry key="connectionTimeMillis">1000</entry>
<entry key="databaseURL">localhost:2097</entry>

Isn’t that cool? :-) Properties can be stored not only in flat text files, but also in XML format.

Share with the World!