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

Several third-party libraries provide utility methods for working with files. If you prefer the Apache Commons IO library, it’s FileUtils class has several file manipulation utilities.

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

To read the contents of a file line by line into a list of strings, we can use the readLines() method from Apache Commons IO FileUtils class. It accepts the file to read and the character encoding to convert Bytes from the file into characters. It returns the list of strings representing each line in the file and throws IOException in case of an I/O error.

Download Code

2. Using FileUtils.readFileToString(File, Charset) method

Apache Commons IO FileUtils class provides the readFileToString() method that allows you to read the contents of any file into a string using the specified charset for converting Bytes from the file into characters. It throws IOException in case of an I/O error.

Download Code

3. Using IOUtils.toString(FileInputStream, Charset) method

Alternatively, we can use IOUtils class from Apache Commons IO library that has the toString() method. It takes an InputStream and renders its contents as string, as shown below:

Download Code

That’s all about reading file contents with Apache Commons IO library in Java.

 
Also See:

Read contents of a file using Guava library in Java