Reading text files in Java

In Reading text files in Java tutorial we show how to read text files in Java. We use build-in tools including FileReader, InputStreamReader, and Scanner. In addition, we use API from the Apache Commons and Google Guava libraries.

Apache Commons IO is a library of utilities to help with developing IO functionality. Google Guava is set of common libraries for Java; the set includes IO API, too.

The following examples use this text file.

thermopylae.txt
The Battle of Thermopylae was fought between an alliance of Greek city-states, 
led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the 
course of three days, during the second Persian invasion of Greece. 

The file is located in the src/resources/ directory.

Reading text files with FileReader

FileReader is a class used for reading character files. It uses system default character encoding.

ReadTextFileEx.java
package com.zetcode;

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

public class ReadTextFileEx {

    public static void main(String[] args) throws IOException {
        
        String fileName = "src/resources/thermopylae.txt";
        
        try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {

            StringBuilder sb = new StringBuilder();

            String line;
            while ((line = br.readLine()) != null) {

                sb.append(line);

                if (line != null) {
                    sb.append(System.lineSeparator());
                }
            }
            
            System.out.println(sb);
        }
    }
}

The code example reads text from the thermopylae.txt file.

String fileName = "src/resources/thermopylae.txt";

In the fileName variable, we store the path to the file.

try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {

The FileReader takes the file name as a parameter. The FileReader is passed to the BufferedReader, which buffers read operations for better performance. This is a try-with-resources statement which ensures that the resource (the buffered reader) is closed at the end of the statement.

StringBuilder sb = new StringBuilder();

String line;
while ((line = br.readLine()) != null) {

    sb.append(line);

    if (line != null) {
        sb.append(System.lineSeparator());
    }
}

System.out.println(sb);

Printing lines to the console consumes a lot of resources. Therefore, we use the StringBuilder to build the output string and print it in one operation. The System.lineSeparator() returns the system-dependent line separator string.

Reading text files with Files.readAllLines

The Files.readAllLines() method reads all lines from a file. This method ensures that the file is closed when all bytes have been read or an exception is thrown. The bytes from the file are decoded into characters using the specified charset.

Note that this method reads the whole file into the memory; therefore, it may not be suitable for very large files.

ReadTextFileEx2.java
package com.zetcode;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class ReadTextFileEx2 {

    public static void main(String[] args) throws IOException {

        String fileName = "src/resources/thermopylae.txt";

        List<String> lines = Files.readAllLines(Paths.get(fileName), 
                StandardCharsets.UTF_8);

        StringBuilder sb = new StringBuilder();

        for (String line : lines) {
            sb.append(line);
            sb.append(System.lineSeparator());
        }

        System.out.println(sb);
    }
}

The contents of the thermopylae.txt file are read and printed to the console using the Files.readAllLines() method.

Reading text files with Java 8 streaming API

Another option to read text files is to use the Java 8 streaming API. The Files.lines() reads all lines from a file as a stream. The bytes from the file are decoded into characters using the StandardCharsets.UTF-8 charset.

ReadTextFileEx3.java
package com.zetcode;

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

public class ReadTextFileEx3 {

    public static void main(String[] args) throws IOException {
        
        String fileName = "src/resources/thermopylae.txt";
        
        StringBuilder sb = new StringBuilder();
        
        Files.lines(Paths.get(fileName)).forEachOrdered(s -> {
            sb.append(s); 
            sb.append(System.lineSeparator());
        });
        
        System.out.println(sb);
    }
}

The contents of the thermopylae.txt file are read and printed to the console using the Files.lines() method.

Reading text files with Scanner

A Scanner is simple text scanner which can parse primitive types and strings using regular expressions.

ReadTextFileEx4.java
package com.zetcode;

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

public class ReadTextFileEx4 {

    public static void main(String[] args) throws FileNotFoundException {

        String fileName = "src/resources/thermopylae.txt";
        Scanner scan = null;

        try {

            scan = new Scanner(new File(fileName));

            StringBuilder sb = new StringBuilder();

            while (scan.hasNext()) {

                String line = scan.nextLine();
                sb.append(line);
                sb.append(System.lineSeparator());
            }

            System.out.println(sb);
        } finally {

            if (scan != null) {
                scan.close();
            }
        }
    }
}

The example reads a text file using a Scanner.

while (scan.hasNext()) {

    String line = scan.nextLine();
    sb.append(line);
    sb.append(System.lineSeparator());
}

The file is read line by line with the nextLine() method.

Reading text files with InputStreamReader

InputStreamReader is a bridge from byte streams to character streams. It reads bytes and decodes them into characters using a specified charset.

ReadTextFileEx5.java
package com.zetcode;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class ReadTextFileEx5 {

    public static void main(String[] args) throws IOException {

        String fileName = "src/resources/thermopylae.txt";
        BufferedReader br = null;

        try {
            
            String line = null;
            StringBuilder sb = new StringBuilder();

            br = new BufferedReader(new InputStreamReader(
                    new FileInputStream(new File(fileName)), 
                    StandardCharsets.UTF_8));
            
            while ((line = br.readLine()) != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
            }
            
            System.out.println(sb);

        } finally {

            if (br != null) {
                br.close();
            }
        }
    }
}

The example reads a text file using an InputStreamReader.

br = new BufferedReader(new InputStreamReader(
        new FileInputStream(new File(fileName)), 
        StandardCharsets.UTF_8));

The InputStreamReader is created from a FileInputStream, which creates an input stream by opening a connection to an actual file. The InputStreamReader is then passed to a BufferedReader for better efficiency.

Reading text files with Apache commons IOUtils

Apache Commons IO is a library of utilities to assist with developing IO functionality in Java. It contains an IOUtils class, which provides static utility methods for input & output operations.

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

We add this Maven dependency to the pom.xml file.

ReadTextFileEx6.java
package com.zetcode;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.commons.io.IOUtils;

public class ReadTextFileEx6 {

    public static void main(String[] args) throws FileNotFoundException, 
            IOException {
        
        String fileName = "src/main/resources/thermopylae.txt";

        try (FileInputStream inputStream = new FileInputStream(fileName)) {
            
            String allLines = IOUtils.toString(inputStream, "UTF-8");
            System.out.println(allLines);
        }
    }
}

The IOUtils.toString() method gets the contents of an InputStream as a String using the specified character encoding. This method may not be suitable for larger files, since it reads the whole contents into the memory.

In the second example, we read the file contents into a string.

ReadTextFileEx7.java
package com.zetcode;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

public class ReadTextFileEx7 {

    public static void main(String[] args) throws IOException {
        
        String fileName = "src/main/resources/thermopylae.txt";
        
        String content = FileUtils.readFileToString(new File(fileName), "UTF-8");
        System.out.println(content);
    }
}

The FileUtils.readFileToString() method reads the contents of a file into a String. The file is always closed.

Reading text files with Google Guava

Google Guava is a Java helper library which has IO tools, too. Similar to the above Apache commons methods the following two Guava methods would consume a lot of system resources if the file to be read is very large.

<dependencies>

    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>19.0</version>
    </dependency>

</dependencies>

We have used this dependency for the following two projects.

ReadTextFileEx8.java
package com.zetcode;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class ReadTextFileEx8 {
    
    public static void main(String[] args) throws IOException {
        
        String fileName = "src/main/resources/thermopylae.txt";
        
        List<String> lines = Files.readLines(new File(fileName), 
                Charsets.UTF_8);
        
        StringBuilder sb = new StringBuilder();
        
        for (String line: lines) {
            sb.append(line);
            sb.append(System.lineSeparator());
        }
        
        System.out.println(sb);
    }
}

In the example, we read all of the lines from a file with the Files.readLines() method. The method returns a list of strings. A default charset is specified as the second parameter.

In the second example, we read the file contents into a string.

ReadTextFileEx9.java
package com.zetcode;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;

public class ReadTextFileEx9 {

    public static void main(String[] args) throws IOException {

        String fileName = "src/main/resources/thermopylae.txt";

        String content = Files.toString(new File(fileName), Charsets.UTF_8);

        System.out.println(content);
    }
}

The Files.toString() method reads all characters from a file into a string, using the given character set.

Reading a CSV file

If we have structured data, it may be more convenient to use some specific tool. For instance, in case of CSV files we can use the Opencsv library to read them.

<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>3.8</version>
</dependency>

We add the Maven dependency for the Opencsv library.

capitals.csv
City, Country, Population
Bratislava, Slovakia, 432000
Vilnius, Lithuania, 542020
Lisbon, Portugal, 547000
Copenhagen, Denmark, 583000

For this example, we have the capitals.csv file in the src/main/resources/ directory.

ReadCSVFileEx.java
package com.zetcode;

import com.opencsv.CSVReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadCSVFileEx {

    public static void main(String[] args) throws FileNotFoundException,
            IOException {
        
        String fileName = "src/main/resources/capitals.csv";

        CSVReader reader = new CSVReader(new FileReader(fileName));
        String[] nextLine;

        StringBuilder sb = new StringBuilder();
        
        while ((nextLine = reader.readNext()) != null) {

            for (String e : nextLine) {
                sb.append(e);
            }
            
            sb.append(System.lineSeparator());
        }
        
        System.out.println(sb);
    }
}

We read the contents of the capitals.csv file and print them to the console.

CSVReader reader = new CSVReader(new FileReader(fileName));

The CSVReader is a class used for reading CSV files.

while ((nextLine = reader.readNext()) != null) {

    for (String e : nextLine) {
        sb.append(e);
    }
    
    sb.append(System.lineSeparator());
}

We iterate the reader with the readNext() method and build the StringBuilder form the file contents.

In this article, we have read text files in various ways in Java.

You might also be interested in the following related tutorials: Opencsv tutorial, Copying file in Java, Java tutorial, Joining strings with Java 8's StringJoiner, Reading a web page in Java, or Introduction to Google Guava.