Java Read Reader Line by Line with LineIterator using Apache Commons IO
Tags: LineIterator IOUtils Apache Commons Apache Commons IO Reader FileReader
In this Java tutorial we learn how to use the IOUtils class in Apache Commons IO library to read an Reader object line by line via LineIterator class.
How to add Apache Commons IO library to your Java project
To use the Apache Commons IO library in the Gradle build project, add the following dependency into the build.gradle file.
implementation 'commons-io:commons-io:2.8.0'
To use the Apache Commons IO library in the Maven build project, add the following dependency into the pom.xml file.
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
To have more information about the Apache Commons IO library you can visit the library home page at commons.apache.org/proper/commons-io/
How to use LineIterator to read a Reader object using IOUtils class
For example we have a text file located at D:\Data\data.txt.
Simple Solution
Java Tutorials
Apache Commons IO Tutorials
In the following Java program, we use the IOUtils.lineIterator() method to read the Reader object of the file into a LineIterator object. Then read file content line by line and print it to the output.
LineIteratorReader.java
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class LineIteratorReader {
public static void main(String... args) {
try {
Reader reader = new FileReader("D:\\Data\\data.txt");
LineIterator lineIterator = IOUtils.lineIterator(reader);
while(lineIterator.hasNext()) {
String line = lineIterator.nextLine();
System.out.println(line);
}
IOUtils.close(reader);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Simple Solution
Java Tutorials
Apache Commons IO Tutorials
Happy Coding 😊