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();
        }
    }
}