How do I read file using FileInputStream?

The following example use the java.io.FileInputStream class to read contents of a text file. We’ll read a file located in the temporary directory defined by operating system. This temporary directory can be accessed using the java.io.tmpdir system property.

package org.kodejava.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamDemo {
    public static void main(String[] args) {
        // Get the temporary directory. We'll read the data.txt file
        // from this directory.
        String tempDir = System.getProperty("java.io.tmpdir");
        File file = new File(tempDir + "/data.txt");

        StringBuilder builder = new StringBuilder();
        FileInputStream fis = null;
        try {
            // Create a FileInputStream to read the file.
            fis = new FileInputStream(file);

            int data;
            // Read the entire file data. When -1 is returned it
            // means no more content to read.
            while ((data = fis.read()) != -1) {
                builder.append((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // Print the content of the file
        System.out.println("File Contents = " + builder);
    }
}

The content read from the input stream will be appended into a StringBuilder object. At the end of the snippet the content of the will be converted into string using the toString() method.

Here are the content of our data.txt file.

File Contents = Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

How do I use a FileChannel to read data into a Buffer?

The example below show how to use a FileChannel to read some data into a Buffer. We create a FileChannel from a FileInputStream instance. Because a channel reads data into buffer we need to create a ByteBuffer and set its capacity. Read data from a channel into buffer using the FileChannel.read() method.

To read out the data from the buffer we need to flip the buffer first using the Buffer.flip() method. The method will change the buffer from writing-mode into reading-mode. After the entire buffer is read clear the buffer using the clear() method call.

package org.kodejava.io;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileRead {
    public static void main(String[] args) {
        String path = "D:/Temp/source.txt";
        try (FileInputStream fis = new FileInputStream(path);
             FileChannel fileChannel = fis.getChannel()) {

            ByteBuffer buffer = ByteBuffer.allocate(64);

            int bytesRead = fileChannel.read(buffer);
            while (bytesRead != -1) {
                buffer.flip();

                while (buffer.hasRemaining()) {
                    System.out.print((char) buffer.get());
                }

                buffer.clear();
                bytesRead = fileChannel.read(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I read a file into byte array?

package org.kodejava.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ReadFileIntoByteArray {
    public static void main(String[] args) throws IOException {
        File file = new File("README.md");
        try (InputStream is = new FileInputStream(file)) {
            if (file.length() > Integer.MAX_VALUE) {
                throw new IOException("File is too large.");
            }

            int offset = 0;
            int bytesRead;
            byte[] bytes = new byte[(int) file.length()];
            while (offset < bytes.length
                    && (bytesRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += bytesRead;
            }
        }
    }
}

How do I display file contents in hexadecimal?

In this program we read the file contents byte by byte and then print the value in hexadecimal format. As an alternative to read a single byte we can read the file contents into array of bytes at once to process the file faster.

package org.kodejava.io;

import java.io.FileInputStream;

public class HexDumpDemo {
    public static void main(String[] args) throws Exception {
        // Open the file using FileInputStream
        String fileName = "F:/Wayan/Kodejava/kodejava-example/data.txt";
        try (FileInputStream fis = new FileInputStream(fileName)) {
            // A variable to hold a single byte of the file data
            int i = 0;

            // A counter to print a new line every 16 bytes read.
            int count = 0;

            // Read till the end of the file and print the byte in hexadecimal
            // valueS.
            while ((i = fis.read()) != -1) {
                System.out.printf("%02X ", i);
                count++;

                if (count == 16) {
                    System.out.println();
                    count = 0;
                }
            }
        }
    }
}

And here are some result from the file read by the above program.

31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 
37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 
33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 
39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 
35 36 37 38 39 30 0A 

How do I copy file?

This example demonstrates how to copy file using the Java IO library. Here we will use the java.io.FileInputStream and it’s tandem the java.io.FileOutputStream class.

package org.kodejava.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopyDemo {
    public static void main(String[] args) {
        // Create an instance of source and destination files
        File source = new File("source.pdf");
        File destination = new File("target.pdf");

        try (FileInputStream fis = new FileInputStream(source);
             FileOutputStream fos = new FileOutputStream(destination)) {
            // Define the size of our buffer for buffering file data
            byte[] buffer = new byte[4096];
            int read;
            while ((read = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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