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 store objects in file?

This example demonstrates how to use the java.io.ObjectOutputStream and java.io.ObjectInputStream classes to write and read a serialized object. We will create a Book that implements java.io.Serializable interface. The Book class has a constructor that accept all the book detail information.

To write an object to a stream we call the writeObject() method of the ObjectOutputStream class and pass the serialized object to it. To read the object back we call the readObject() method of the ObjectInputStream class.

package org.kodejava.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectStoreExample {

    public static void main(String[] args) {
        // Create instances of FileOutputStream and ObjectOutputStream.
        try (FileOutputStream fos = new FileOutputStream("books.dat");
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {

            // Create a Book instance. This book object then will be stored in
            // the file.
            Book book = new Book("0-07-222565-3", "Hacking Exposed J2EE & Java",
                    "Art Taylor, Brian Buege, Randy Layman");

            // By using writeObject() method of the ObjectOutputStream we can
            // make the book object persistent on the books.dat file.
            oos.writeObject(book);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // We have the book saved. Now it is time to read it back and display
        // its detail information.
        try (FileInputStream fis = new FileInputStream("books.dat");
             ObjectInputStream ois = new ObjectInputStream(fis)) {

            // To read the Book object use the ObjectInputStream.readObject() method.
            // This method return Object type data, so we need to cast it back the
            // origin class, the Book class.
            Book book = (Book) ois.readObject();
            System.out.println(book.toString());

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

// The book object will be saved using ObjectOutputStream class and to be read
// back using ObjectInputStream class. To enable an object to be written to a
// stream we need to make the class implements the Serializable interface.
class Book implements Serializable {
    private final String isbn;
    private final String title;
    private final String author;

    public Book(String isbn, String title, String author) {
        this.isbn = isbn;
        this.title = title;
        this.author = author;
    }

    @Override
    public String toString() {
        return "Book{" +
                "isbn='" + isbn + '\'' +
                ", title='" + title + '\'' +
                ", author='" + author + '\'' +
                '}';
    }
}

The result of the code snippet above is:

Book{isbn='0-07-222565-3', title='Hacking Exposed J2EE & Java', author='Art Taylor, Brian Buege, Randy Layman'}

How do I use DataInputStream and DataOutputStream?

java.io.DataOutputStream and java.io.DataInputStream give us the power to write and read primitive data type to a media such as file. Both of these classes have the corresponding methods to write primitive data type and to read it back.

Using this class make it easier to read int, float, double data and others without needing to interpret if the data should be an int or a float data. Let’s see our code below.

package org.kodejava.io;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class PrimitiveStreamExample {

    public static void main(String[] args) {
        // Prepares some data to be written to a file.
        int cityIdA = 1;
        String cityNameA = "Green Lake City";
        int cityPopulationA = 500000;
        float cityTempA = 15.50f;

        int cityIdB = 2;
        String cityNameB = "Salt Lake City";
        int cityPopulationB = 250000;
        float cityTempB = 10.45f;

        /*
        Create an instance of FileOutputStream with cities.dat as the file
        name to be created. Then we pass the input stream object in the
        DataOutputStream constructor.
        */
        try (FileOutputStream fos = new FileOutputStream("cities.dat");
             DataOutputStream dos = new DataOutputStream(fos)) {

            /*
             Below we write some data to the cities.dat. DataOutputStream
             class have various method that allow us to write primitive type
             data and string. There are method called writeInt(),
             writeFloat(), writeUTF(), etc.
            */
            dos.writeInt(cityIdA);
            dos.writeUTF(cityNameA);
            dos.writeInt(cityPopulationA);
            dos.writeFloat(cityTempA);

            dos.writeInt(cityIdB);
            dos.writeUTF(cityNameB);
            dos.writeInt(cityPopulationB);
            dos.writeFloat(cityTempB);
        } catch (IOException e) {
            e.printStackTrace();
        }

        /*
         Now we have a cities.dat file with some data in it. Next you'll see
         how easily we can read back this data and display it. Just like the
         DataOutputStream the DataInputStream class have the corresponding
         read methods to read data from the file. Some method names
         are readInt(), readFloat(), readUTF(), etc.
        */
        try (FileInputStream fis = new FileInputStream("cities.dat");
             DataInputStream dis = new DataInputStream(fis)) {

            // Read the first data
            int cityId1 = dis.readInt();
            String cityName1 = dis.readUTF();
            int cityPopulation1 = dis.readInt();
            float cityTemperature1 = dis.readFloat();

            printOut(cityId1, cityName1, cityPopulation1, cityTemperature1);

            // Read the second data
            int cityId2 = dis.readInt();
            String cityName2 = dis.readUTF();
            int cityPopulation2 = dis.readInt();
            float cityTemperature2 = dis.readFloat();

            printOut(cityId2, cityName2, cityPopulation2, cityTemperature2);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void printOut(int cityId1, String cityName1, int cityPopulation1, float cityTemperature1) {
        System.out.println("Id: " + cityId1);
        System.out.println("Name: " + cityName1);
        System.out.println("Population: " + cityPopulation1);
        System.out.println("Temperature: " + cityTemperature1);
    }
}

The generated result of our program are:

Id: 1
Name: Green Lake City
Population: 500000
Temperature: 15.5
Id: 2
Name: Salt Lake City
Population: 250000
Temperature: 10.45