JavaDevNotes.com

Java Read Text File Examples

Reading text files is one of the most common file manipulation task in Java. Here are some examples of how to read text files in Java using long method and also shortcuts in recent Java version.

Read Text File Line Per Line

Here is a simple Java program that reads a text file line by line and display each line on the console using System.out.println.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
 * A simple example program that reads a text file line by line and display each line.
 */
public class ReadTextFileExample {
    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("C:\\temp\\testfile.txt"));
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

A problem with the above approach is that our code explicitly closes the reader after use. This is very tedious and we can use Java 7's try with resources feature. The modified sample is below:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
 * A simple example program that reads a text file line by line using Java 7's try with resource.
 */
public class ReadTextFileExample {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("C:\\temp\\testfile.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
This is much shorter. The resource we opened inside the parenthesis in try statement will be automatically closed when exiting try. This will greatly simplify and shorten our code without compromising safety.

A shorter code for reading text file in Java 7 using Files.readAllLines. But this will load all lines into memory, so use it with caution.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
/**
 * A simple example program that reads a text file line by line using Files.readAllLines.
 */
public class ReadTextFileExample {
    public static void main(String[] args) throws IOException {
        List<String> lines = Files.readAllLines(Paths.get("c:\\temp\\testfile.txt"));
        for (String line : lines) {
            System.out.println(line);
        }
    }
}

Another alternative code for reading a text file using Java 8 and Files.lines and streams.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
 * A simple example program that reads a text file line by line using Java 8.
 */
public class ReadTextFileExample {
    public static void main(String[] args) throws IOException {
        Files.lines(Paths.get("c:\\temp\\testfile.txt")).forEach(System.out::println);
    }
}

Read Text File Into A String

Here is a simple program that loads the contents of a text file into a String by reading each line and concatenating the results using StringBuilder.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
 * A simple example program that reads a into a String using StringBuilder.
 */
public class ReadTextFileExample {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("C:\\temp\\testfile.txt"));
            String line;
            while ((line = br.readLine()) != null) {
                if (sb.length() > 0) {
                    sb.append("\n");
                }
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        String contents = sb.toString();
        System.out.println(contents);
    }
}

Here is an alternative implementation of reading a text file into a String using Java 7's Files.readAllBytes.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
 * A simple example program that reads a into a String using Java 7's Files.readAllBytes.
 */
public class ReadTextFileExample {
    public static void main(String[] args) throws IOException {
        String contents = new String(Files.readAllBytes(Paths.get("C:\\temp\\testfile.txt")));
        System.out.println(contents);
    }
}

Another implementation using Java 7's Files.readAllLines and StringBuilder.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
/**
 * A simple example program that reads a into a String using Java 7's Files.readAllLines.
 */
public class ReadTextFileExample {
    public static void main(String[] args) throws IOException {
        List<String> lines = Files.readAllLines(Paths.get("C:\\temp\\testfile.txt"));
        StringBuilder sb = new StringBuilder();
        for (String line : lines) {
            if (sb.length() > 0) {
                sb.append("\n");
            }
            sb.append(line);
        }
        String contents = sb.toString();
        System.out.println(contents);
    }
}

A more concise way of reading a text file to a String is using streams of Java 8.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
/**
 * A simple example program that reads a text file into a String using Files.lines and stream.
 */
public class ReadTextFileExample {
    public static void main(String[] args) throws IOException {
        String contents = Files.lines(Paths.get("c:\\temp\\testfile.txt")).collect(Collectors.joining("\n"));
        System.out.println(contents);
    }
}