Provides a flexible way to work with a line-based file.

Class Declaration

Following is the declaration for org.apache.commons.io.LineIterator Class −

  1. public class LineIterator
  2. extends Object implements Iterator<String>, Closeable

Example of LineIterator Class

Here is the input file we need to parse −

  1. Welcome to TutorialsPoint. Simply Easy Learning.
  2. Learn web technologies,
  3. prepare exams,
  4. code online,
  5. all at one place.

IOTester.java

  1. import java.io.File;
  2. import java.io.IOException;
  3.  
  4. import org.apache.commons.io.FileUtils;
  5. import org.apache.commons.io.LineIterator;
  6.  
  7. public class IOTester {
  8. public static void main(String[] args) {
  9. try {
  10. usingLineIterator();
  11. } catch(IOException e) {
  12. System.out.println(e.getMessage());
  13. }
  14. }
  15.  
  16. public static void usingLineIterator() throws IOException {
  17. //get the file object
  18. File file = FileUtils.getFile("input.txt");
  19.  
  20. try(LineIterator lineIterator = FileUtils.lineIterator(file)) {
  21. System.out.println("Contents of input.txt");
  22. while(lineIterator.hasNext()) {
  23. System.out.println(lineIterator.next());
  24. }
  25. }
  26. }
  27. }

Output

It will print the following result.

  1. Contents of input.txt
  2. Welcome to TutorialsPoint. Simply Easy Learning.
  3. Learn web technologies,
  4. prepare exams,
  5. code online,
  6. all at one place.