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>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
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!
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 theFileUtils.lineIterator()
method from the Apache Commons IO.