Grails Cookbook - A collection of tutorials and examples

Read Text File in Java

When we are programming, we typically face the scenario where we need to read text files. For example, reading data from a file or reading configuration. There are some long methods, and there are some short methods. Below are some examples on how we can read text files in Java.

Read Into A String

Sometimes we just want to load the contents of a text file straight into a String variable. Check out the simple written program. Understand that through reading each line and interconnecting the results, the program will load the text file's contents into a String using Stringbuilder.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
 * This is a simple example program that reads a line into a String using StringBuilder.
 */
public class TextFileExample1 {
    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);
    }
}
Java 7's Files.readAllBytes is another application for reading a text file into a String.
Check the code below:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
 * This is a simple example program that reads a text file into a String using Java 7's Files.readAllBytes.
 */
public class TextFileExample2 {
    public static void main(String[] args) throws IOException {
        String contents = new String(Files.readAllBytes(Paths.get("C:\\temp\\testfile.txt")));
        System.out.println(contents);
    }
}
Understand that the code below is another way of reading a text file into a String 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;
/**
 * This is a simple example program that reads a text file into a String using Java 7's Files.readAllLines.
 */
public class TextFileExample3 {
    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);
    }
}
Lastly, this is a brief method using streams of Java 8.
Check out the code below:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
/**
 * This is a simple example program that reads a text file into a String using Files.lines and stream.
 */
public class TextFileExample4 {
    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);
    }
}

Reading Per Line

Sometimes, we don't want to read a text file into a String, but to process it line by line. Using System.out.println, this program will read a text file line by line and will display it on the console. Check out the program below:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
 * This is a simple example program that reads a text file line by line and display each line on the console using System.out.println.
 */
public class TextFileExample5 {
    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();
            }
        }
    }
}
There is a conflict with the approach written above, that is, our code will close the reader after using it. A slight problem also is that this process is boring. What we can use is Java 7's try with resources feature.

Check out the altered sample below:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
 * This is a simple example program that reads a text file line by line using Java 7's try with resource.
 */
public class TextFileExample6 {
    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();
        }
    }
}
If we take a look at the resource we've opened within the parenthesis in try statement, we would understand that it will close automatically while exiting try. Also, notice that the codes are shorter compared to the previous example written above, not only it is short but it will simplify our code without having to worry about safety.

Another code we can use is Files.readAllLines in Java 7. It's also a short code for reading text file. Remember the part where System.out.println will read a file text line by line and will display also line by line on the console? Files.readAllLines will load all lines into memory, so we need to be cautious about our memory's capacity when we use this.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
/**
 * This is a simple example program that reads a text file line by line using Files.readAllLines.
 */
public class TextFileExample7 {
    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);
        }
    }
}
Now, we go to Java 8 and Files.lines and stream. This is an optional substitute code we can also utilize for reading a text file.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
 * This is a simple example program that reads a text file line by line using Java 8.
 */
public class TextFileExample8 {
    public static void main(String[] args) throws IOException {
        Files.lines(Paths.get("c:\\temp\\testfile.txt")).forEach(System.out::println);
    }
}