In this post under Apache Commons IO, I will show with example how to read file contents using Iterator.
“IOUtils” provides a static method named “lineIterator” which reads the file and returns an “Iterator” object. Each item returned by this iterator represent a line in the file.
Using the “Iterator” object we can iterate the contents of the file.
Below is the complete main code for your reference
Main class
package ioutils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Example6 {
public static void main(String[] args) throws IOException {
File file = new File("Quotes.txt");
try(FileReader fileReader = new FileReader(file)) {
LineIterator lineIterator = IOUtils.lineIterator(fileReader);
while(lineIterator.hasNext()) {
System.out.println(lineIterator.next());
}
}
}
}
In the above code, at line 12, I create an instance of “File” class.
At line 13, I created an instance of “FileReader” using the file object.
At line 14, I call “IOUtils” “lineIterator” static method. It takes the “FileReader” object as an argument.
This method returns an instance of “LineIterator” class.
This “LineIterator” class object will be used to iterate through contents of the file.
In this way we can iterate through the contents of the file.