Java – How to Read a Text File

Many different ways to read a text file in Java.

1. Introduction

There are several ways of reading text from a file in Java. Let us learn about them. We also show you how to read a file line by line.

2. Read and Print a Text File

The following code shows the most basic way of reading a text file in java. We use a FileReader for the purpose.

First we use a try-with-resources block to automatically close the opened file at the end of the block. Next we use a character array to read the text in. Finally the character arrays is converted to a String and printed to System.out.

try (FileReader in = new FileReader(fileName)) {
    char[] cbuf = new char[2048];
    int len;
    while ((len = in.read(cbuf)) != -1) {
    String str = new String(cbuf, 0, len);
    System.out.print(str);
    }
}

Some exceptions are possible with this code – including FileNotFoundException while opening the file, and IOException while reading the file contents. Catch the exceptions if you have any special handling to do.

3. Read UTF-16 Encoded Text File

While the above code suffices to read text from a file, what if you need to read a text file encoded in a different encoding? The code above uses the platform-default encoding to read the file. On my system this is UTF-8; it might be different on yours. Regardless, we should know how to read a text file in a different encoding.

The key to opening a file with a different encoding is a two-step process as follows: open an InputStream to the file and use InputStreamReader to specify the encoding.

String encoding = "UTF-16";
FileInputStream fin = new FileInputStream(fileName);
InputStreamReader in = new InputStreamReader(fin, encoding);

Other than this change, reading a file is now as easy as before. Here is the complete code:

try (FileInputStream fin = new FileInputStream(fileName);
     InputStreamReader in = new InputStreamReader(fin, "UTF-16");) {
    char[] cbuf = new char[2048];
    int len;
    while ((len = in.read(cbuf)) != -1) {
    String str = new String(cbuf, 0, len);
    System.out.print(str);
    }
}

4. Read Text File using nio.Files

If you want to read the complete file into memory (into a String), here is a simple way to do it. Not advisable if the file is large. You can specify a different encoding if the file you are reading is not UTF-8.

byte[] buf = Files.readAllBytes(Paths.get(fileName));
String str = new String(buf,"UTF-8");
System.out.print(str);

Here are some more ways of reading a complete file into memory.

5. Read File Line by Line

Let us now look at several methods where we can read a text file line by line. The simplest way is shown below (possible from Java 1.0) – Use BufferedReader.readLine() method.

try (BufferedReader in = new BufferedReader(new FileReader(fileName))){
    String line;
    while ((line = in.readLine()) != null) {
    System.out.println(line);
    }
}

6. Stream Lines of a Text File

With Java 8 enhancements, we can stream all the lines of a text file and use it as follows:

try (BufferedReader in = new BufferedReader(new FileReader(fileName))){
    in.lines().forEach(System.out::println);
}

7. Use Scanner to Read Lines

Java provides a class called Scanner which can be used to read all the lines of a file in a loop as follows:

try (Scanner scanner = new Scanner(Paths.get(fileName), "UTF-8")) {
    while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    System.out.println(line);
    }
}

8. Read File Lines into a List

Or how about using Files.readAllLines() to read all the lines of a file into a List.

List<String> lines = Files.readAllLines(Paths.get(fileName));
lines
    .stream()
    .forEach(System.out::println);

Summary

This article demonstrated how to read a text file in Java. We also learned how to open and read a text file in a different encoding. Sometimes reading the whole contents of a file is required. This can be accomplished using several methods as shown above.

Leave a Reply

Your email address will not be published. Required fields are marked *