How to Read Files in Java

Java provides several methods to read files. Each of these methods is appropriate for reading different types of files in different situations. Some are better for reading longer files, others are better for reading shorter ones, etc.

In this tutorial, we will be using the following Java classes to read files

  • BufferedReader
  • Files
  • Scanner

Throughout the tutorial, we are using a file stored in the src directory where the path to the file is src/file.txt.

Store several lines of text in this file before proceeding.

Reading Text Files in Java with BufferedReader

The BufferedReader class reads a character-input stream. It buffers characters in a buffer with a default size of 8 KB to make the reading process more efficient. If you want to read a file line by line, using BufferedReader is a good choice.

BufferedReader is efficient in reading large files.

import java.io.*;

public class FileReaderWithBufferedReader {

    public static void main(String[] args) throws IOException{We
        String file = "src/file.txt";
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

        String curLine;
        while ((curLine = bufferedReader.readLine()) != null){
            //process the line as required
            System.out.println(curLine);
        }
        bufferedReader.close();
    }
}

The readline() method returns null when the end of the file is reached.

Reading UTF-8 Encoded File in Java with BufferedReader

We can use the BufferedReader class to read a UTF-8 encoded file.

This time, we pass an InputStreamReader object when creating a BufferedReader instance.

import java.io.*;

public class EncodedFileReaderWithBufferedReader {

    public static void main(String[] args) throws IOException {
        String file = "src/fileUtf8.txt";
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));

        String curLine;
        while ((curLine = bufferedReader.readLine()) != null){
            //process the line as you require
            System.out.println(curLine);
        }
    }
}

Using Java Files Class to Read a File

Java Files class, introduced in Java 7 in Java NIO, consists fully of static methods that operate on files.

Using Files class, you can read the full content of a file into an array. This makes it a good choice for reading smaller files.

Let’s see how we can use Files class in both these scenarios.

Reading Small Files in Java with Files Class

The readAllLines() method of the Files class allows reading the whole content of the file and stores each line in an array as strings.

You can use the Path class to get the path to the file since the Files class accepts the Path object of the file.

import java.io.IOException;
import java.nio.file.*;
import java.util.*;

public class SmallFileReaderWithFiles {

    public static void main(String[] args) throws IOException {
        String file = "src/file.txt";
        Path path = Paths.get(file);
        List<String> lines = Files.readAllLines(path);
    }
}

You can use readAllBytes() to retrieve the data stored in the file to a byte array instead of a string array.

byte[] bytes = Files.readAllBytes(path);

Reading Large Files in Java with Files Class

If you want to read a large file with the Files class, you can use the newBufferedReader() method to obtain an instance of BufferedReader class and read the file line by line using a BufferedReader.

import java.io.*;
import java.nio.file.*;

public class LargeFileReaderWithFiles {

    public static void main(String[] args) throws IOException {
        String file = "src/file.txt";
        Path path = Paths.get(file);
        BufferedReader bufferedReader = Files.newBufferedReader(path);

        String curLine;
        while ((curLine = bufferedReader.readLine()) != null){
            System.out.println(curLine);
        }
        bufferedReader.close();
    }
}

Reading Files with Files.lines()

Java 8 introduced a new method to the Files class to read the whole file into a Stream of strings.

import java.io.IOException;
import java.nio.file.*;
import java.util.stream.Stream;

public class FileReaderWithFilesLines {

    public static void main(String[] args) throws IOException {
        String file = "src/file.txt";
        Path path = Paths.get(file);
        Stream<String> lines = Files.lines(path);

        lines.forEach(s -> System.out.println(s));
        lines.close();
    }
}

Reading Text Files in Java with Scanner

The Scanner class breaks the content of a file into parts using a given delimiter and reads it part by part. This approach is best suited for reading content that is separated by a delimiter.

For example, the Scanner class is ideal for reading a list of integers separated by white spaces or a list of strings separated by commas.

The default delimiter of the Scanner class is whitespace. But you can set the delimiter to another character or a regular expression. It also has various next methods, such as next(), nextInt(), nextLine(), and nextByte(), to convert content into different types.

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

public class FileReaderWithScanner {

    public static void main(String[] args) throws IOException{
        String file = "src/file.txt";
        Scanner scanner = new Scanner(new File(file));
        scanner.useDelimiter(" ");

        while(scanner.hasNext()){
            String next = scanner.next();
            System.out.println(next);
        }
        scanner.close();
    }
}

In the above example, we set the delimiter to whitespace and use the next() method to read the next part of the content separated by whitespace.

Reading an Entire File

You can use the Scanner class to read the entire file at once without running a loop. You have to pass “\\Z” as the delimiter for this.

scanner.useDelimiter("\\Z");
System.out.println(scanner.next());
scanner.close();

Conclusion

As you saw in this tutorial, Java offers many methods that you can choose from according to the nature of the task at your hand to read text files. You can use BufferedReader to read large files line by line.

If you want to read a file that has its content separated by a delimiter, use the Scanner class.

Also you can use Java NIO Files class to read both small and large files.