There are multiple ways to read a file in Java. This article will make use of classes available in plain Java such as FileReader, BufferedReader, or Scanner. We will also show how to use utility libraries like Guava and Apache Commons IO to read files efficiently. Every approach is a little different and it is up to you what method suits you.
BufferedReader class allows us to read characters from the file using buffering. This class makes the use of a character-based stream provided by FileReader.
Note that before running the code, a text file named frontbackend.txt is required to be created in /tmp folder.
In this example we used readLine() method that reads line-by-line from the input stream and when the end of the file is reached it returns null.
3. Using FileReader to read a File
Using FileReader not wrapped with BufferedReader is another but less efficient method to read a file in Java.
In this example we used FileReader to operate over a character-based stream with the file content. Each character is appended to the StringBuilder and after the end of the file is reached we display the content of the whole file.
4. Reading a File with Scanner
Scanner is a class that parses primitive types and Strings using a delimiter pattern to break it into tokens. The default delimiter is whitespace.
In this example we used Scanner to read the content from a file in a loop, but we can simplify that by using a delimiter Z that means the end of the input.
5. Reading File using DataInputStream
Using DataInputStream allows us to read bytes from the input file. This class operates on the byte-based stream.
In this example we read all bytes from the file at once and create a String object from that byte array.
6. Using java.nio.file.Files to read a File
JDK 8 comes with a Files class that allows us to read all lines from the file using a single method.
In this example we made the use of Files.readAllLines(...) method. We joined returned lines into one String, and printed it to the console.
7. Read a File with Guava
Guava is a utility library with a bunch of methods for common I/O operations. It provides interface very similar to java.nio.file.Files class.
In this example we used the Files.readLines(...) method, available in Guava, to read lines of the file. Then we used the String.join(...) method from plain Java to join all lines into a single String object.
8. Reading a File using Apache Commons IO library
Apache Commons IO is another very popular library that comes with a method that can read the whole file directly to the String object.
In this example we used IOUtils.toString(...) method from Apache Commons IO that returns file content as a String. All necessary I/O operations are done transparently.
In this article we showcased several ways to read a file in Java. We used methods available in plain Java and popular libraries like Guava and Apache Commons IO.