How do I read text file content line by line to a List of Strings using Commons IO?

The following example show how to use the Apache Commons IO library to read a text file line by line to a List of String. In the code snippet below we will read the contents of a file called sample.txt using FileUtils class. We use FileUtils.readLines() method to read the contents line by line and return the result as a List of Strings.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

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

public class ReadFileToListSample {
    public static void main(String[] args) {
        // Create a file object of sample.txt
        File file = new File("README.md");

        try {
            List<String> contents = FileUtils.readLines(file, "UTF-8");

            // Iterate the result to print each line of the file.
            for (String line : contents) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.14.0</version>
</dependency>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.