Reading file contents as a List of Strings

In this post under Apache Commons IO, I will show with example how to read file contents into a List of Strings.

To implement this requirement, the library class “IOUtils” provide with a method named “readLines”

This method takes a “FileReader” instance as an argument and return a list of Strings, where each String represents a line in text.

Below is the complete main code for your references

Main class

package ioutils;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

public class Example9 {
    public static void main(String[] args) throws IOException {
        File file = new File("Quotes.txt");
        try(FileReader fileReader = new FileReader(file)) {
            List<String> lines = IOUtils.readLines(fileReader);
            for(String line : lines) {
                System.out.println(line);
            }
        }
    }
}

In the above, I create an instance “File” class.

In try with resource block I create an instance of “FileReader” class.

At line 14, I call “readLines” and pass the “fileReader” instance as an argument.

This method returns file content as List of Strings, where each String represents a line in text.

In this way, we can use “readLines” method available in “IOUtils” class.

Leave a comment