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

2 Comments

  1. Hi Wayan,

    I too am a programmer, runner and recreational diver. If you ever make it to Florida you should dive our reefs on the Atlantic coast. 🙂

    Nice tutorial on reading a file with FileUtils. You should change the title from “read line by line” to “into list of String” just like you named your class. A list of string needs to allocate all of the memory required to hold the entire contents of the file in memory. If you were to read a very large file using this method, one whose size exceeds the available heap, this method would fail with an out of memory exception. A line by line solution implies that only one line of the file would be kept in memory at a given moment in time. This would allow for reading a file of any size so long as the largest single line of the file fits into memory.

    Keep up the great work!

    Reply
    • Hi Adam,

      Thanks for the invitation, one day maybe ?

      You are right that this example must not be used to read large files. To read large file we better use streaming like using the java.util.Scanner or using the FileUtils.lineIterator() method from the Apache Commons IO.

      Reply

Leave a Reply

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