Java IO - Reading a File

May 24, 2020 No comments Java IO Java File Read

1. Introduction

There are multiple ways to read a file in Java. This article will make use of classes available in plain Java such as FileReader, BufferedReader, or Scanner. We will also show how to use utility libraries like Guava and Apache Commons IO to read files efficiently. Every approach is a little different and it is up to you what method suits you.

This article is a part of the Java I/O Tutorial.

2. Reading a File using BufferedReader

BufferedReader class allows us to read characters from the file using buffering. This class makes the use of a character-based stream provided by FileReader.

package com.frontbackend.java.io.read;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileUsingBufferedReader {

    public static void main(String[] args) throws IOException {
        File file = new File("/tmp/frontbackend.txt");

        BufferedReader br = new BufferedReader(new FileReader(file));

        StringBuilder fileContent = new StringBuilder();
        String st;
        while ((st = br.readLine()) != null) {
            fileContent.append(st);
        }

        System.out.println(fileContent.toString());
    }
}

Note that before running the code, a text file named frontbackend.txt is required to be created in /tmp folder.

In this example we used readLine() method that reads line-by-line from the input stream and when the end of the file is reached it returns null.

3. Using FileReader to read a File

Using FileReader not wrapped with BufferedReader is another but less efficient method to read a file in Java.

package com.frontbackend.java.io.read;

import java.io.FileReader;
import java.io.IOException;

public class ReadFileUsingFileReader {

    public static void main(String[] args) throws IOException {
        FileReader fileReader = new FileReader("/tmp/frontbackend.txt");

        StringBuilder fileContent = new StringBuilder();
        int i;
        while ((i = fileReader.read()) != -1) {
            fileContent.append((char) i);
        }

        System.out.println(fileContent.toString());
    }
}

In this example we used FileReader to operate over a character-based stream with the file content. Each character is appended to the StringBuilder and after the end of the file is reached we display the content of the whole file.

4. Reading a File with Scanner

Scanner is a class that parses primitive types and Strings using a delimiter pattern to break it into tokens. The default delimiter is whitespace.

package com.frontbackend.java.io.read;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class ReadFileUsingScanner {

    public static void main(String[] args) throws IOException {
        File file = new File("/tmp/frontbackend.txt");
        Scanner sc = new Scanner(file);
        StringBuilder fileContent = new StringBuilder();

        while (sc.hasNextLine()) {
            fileContent.append(sc.nextLine());
        }

        System.out.println(fileContent.toString());
    }
}

In this example we used Scanner to read the content from a file in a loop, but we can simplify that by using a delimiter Z that means the end of the input.

package com.frontbackend.java.io.read;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class ReadFileUsingScanner {

    public static void main(String[] args) throws IOException {
        File file = new File("/tmp/frontbackend.txt");
        Scanner sc = new Scanner(file);
        sc.useDelimiter("\\Z"); 

        System.out.println(sc.next()); 
    }
}

5. Reading File using DataInputStream

Using DataInputStream allows us to read bytes from the input file. This class operates on the byte-based stream.

package com.frontbackend.java.io.read;

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

public class ReadFileUsingDataInputStream {

    public static void main(String[] args) throws IOException {
        File file = new File("/tmp/frontbackend.txt");

        String fileContent = null;

        DataInputStream reader = new DataInputStream(new FileInputStream(file));
        int bytesToRead = reader.available();
        if (bytesToRead > 0) {
            byte[] bytes = new byte[bytesToRead];
            reader.read(bytes);
            fileContent = new String(bytes);
        }

        System.out.println(fileContent);
    }
}

In this example we read all bytes from the file at once and create a String object from that byte array.

6. Using java.nio.file.Files to read a File

JDK 8 comes with a Files class that allows us to read all lines from the file using a single method.

package com.frontbackend.java.io.read;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class ReadFileUsingFiles {

    public static void main(String[] args) throws IOException {
        File file = new File("/tmp/frontbackend.txt");
        String fileContent = String.join("", Files.readAllLines(file.toPath(), , StandardCharsets.UTF_8));

        System.out.println(fileContent);
    }
}

In this example we made the use of Files.readAllLines(...) method. We joined returned lines into one String, and printed it to the console.

7. Read a File with Guava

Guava is a utility library with a bunch of methods for common I/O operations. It provides interface very similar to java.nio.file.Files class.

package com.frontbackend.java.io.read;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import com.google.common.io.Files;

public class ReadFileUsingGuava {

    public static void main(String[] args) throws IOException {
        File file = new File("/tmp/frontbackend.txt");

        String fileContent = String.join("", Files.readLines(file, StandardCharsets.UTF_8));
        System.out.println(fileContent);
    }
}

In this example we used the Files.readLines(...) method, available in Guava, to read lines of the file. Then we used the String.join(...) method from plain Java to join all lines into a single String object.

8. Reading a File using Apache Commons IO library

Apache Commons IO is another very popular library that comes with a method that can read the whole file directly to the String object.

package com.frontbackend.java.io.read;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import org.apache.commons.io.IOUtils;

public class ReadFileUsingIOUtils {

    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("/tmp/frontbackend.txt");
        String fileContent = IOUtils.toString(fis, StandardCharsets.UTF_8);

        System.out.println(fileContent);
    }
}

In this example we used IOUtils.toString(...) method from Apache Commons IO that returns file content as a String. All necessary I/O operations are done transparently.

9. Conclusion

In this article we showcased several ways to read a file in Java. We used methods available in plain Java and popular libraries like Guava and Apache Commons IO.

{{ message }}

{{ 'Comments are closed.' | trans }}