Apache Commons IO - Utility Classes
- Apache Commons IO - IOUtils
- Apache Commons IO - FileUtils
- Apache Commons IO - FilenameUtils
- Apache Commons IO - FileSystemUtils
- Apache Commons IO - IOCase
- Apache Commons IO - LineIterator
Apache Commons IO - Filter Classes
- Apache Commons IO - NameFileFilter
- Apache Commons IO - WildcardFileFilter
- Apache Commons IO - SuffixFileFilter
- Apache Commons IO - PrefixFileFilter
- Apache Commons IO - OrFileFilter
- Apache Commons IO - AndFileFilter
- Apache Commons IO - FileEntry
Apache Commons IO - Comparator Classes
- Apache Commons IO - NameFileComparator
- Apache Commons IO - SizeFileComparator
- LastModifiedFileComparator
Apache Commons IO - Stream Classes
Apache Commons IO - Useful Resources
Apache Commons IO - LineIterator Class
Overview
LineIterator class provides a flexible way to work with a line-based file.
Class Declaration
Following is the declaration for org.apache.commons.io.LineIterator Class −
public class LineIterator extends Object implements Iterator<String>, Closeable
Usage of LineIterator
Get LineIterator using FileUtils.
try(LineIterator lineIterator = FileUtils.lineIterator(file)) {
...
}
Check if line exists using lineIterator.hasNext() method
while(lineIterator.hasNext()) {
...
}
Get the line contents using LineIterator.next() method
String lineContents = lineIterator.next()
Here is the input file we need to parse −
input.txt
Welcome to TutorialsPoint. Simply Easy Learning. Learn web technologies, prepare exams, code online, all at one place.
Example - Print each line of file using LineIterator class
CommonsIoTester.java
package com.tutorialspoint;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
public class CommonsIoTester {
public static void main(String[] args) throws IOException {
//get the file object
File file = FileUtils.getFile("input.txt");
try(LineIterator lineIterator = FileUtils.lineIterator(file)) {
System.out.println("Contents of input.txt");
while(lineIterator.hasNext()) {
System.out.println(lineIterator.next());
}
}
}
}
Output
It will print the following result −
Contents of input.txt Welcome to TutorialsPoint. Simply Easy Learning. Learn web technologies, prepare exams, code online, all at one place.
Advertisements