Java LineIterator-class And Method Code Example


Here's an example of how to use the LineIterator class from the Apache Commons IO library:

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;

public class Example {
    public static void main(String[] args) {
        File file = new File("example.txt");
        try {
            LineIterator it = FileUtils.lineIterator(file, "UTF-8");
            try {
                while (it.hasNext()) {
                    String line = it.nextLine();
                    System.out.println(line);
                }
            } finally {
                LineIterator.closeQuietly(it);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, a LineIterator object is created to read the contents of a file named "example.txt" using the UTF-8 character set. The hasNext() method is used to check if there are more lines to read and the nextLine() method is used to read the next line. The file content is then printed to the console. Finally, the closeQuietly(LineIterator) method is used to close the iterator, suppressing any exceptions that might be thrown.

Note: The LineIterator class provides an easy way to read a file line by line, it is a wrapper class around an Iterator that reads lines from a file. This class provides a convenient and efficient way of reading a large file line by line, without having to load the entire file into memory at once.