This post will discuss how to read the contents of a file using Guava library in Java.

There are several external libraries that provide utility methods for working with files in Java. With Guava library, we can use Files utility class which provides various methods for working with files and directories in Java. The Files class offers several features:

To read contents of a file using the Files class by Guava library, we can use one of the following methods:

1. Using Files.readLines(File, Charset) method

We can use the readLines() method of the Files class that reads all the lines from a file into a mutable List. It accepts two parameters: the file to read from and the charset used to decode the input stream. It throws an IOException if an I/O error occurs. Here is an example of using this method:

Download Code

 
Note that Files.readLines(File, Charset) method is convenient to read all lines in a single operation but does not include line-termination characters. We can easily handle this by joining each of the elements of the list with a line separator, as shown below:

Download Code

2. Using Files.asCharSource(File, Charset) method

Another plausible way of reading files in Guava is using the Files.asCharSource() method. It returns a new CharSource for reading character data from the given file using the given character set. Then we can call the CharSource’s read() method, which reads the contents of this source as a string. This method returns an IOException if an I/O error occurs in the process of reading from this source. This is demonstrated below:

Download Code

 
To read the contents of the CharSource as a list instead of string, we can use the readLines() method, which returns an ImmutableList instance.

Download Code

That’s all about reading the contents of a file with the Guava library in Java.

 
Also See:

Read file contents with Apache Commons IO library in Java