Java Read InputStream Line by Line with LineIterator using Apache Commons IO

Tags: LineIterator IOUtils Apache Commons Apache Commons IO InputStream FileInputStream

In this Java tutorial we learn how to use the IOUtils class in Apache Commons IO library to read an InputStream 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 an InputStream object using IOUtils class

For example we have a text file located at D:\Data\data.txt.

Simple Solution
Java Tutorials
Spring Boot Tutorials

In the following Java program, we use the IOUtils.lineIterator() method to read the InputStream object of the file into a LineIterator object. Then read file content line by line and print it to the output.

LineIteratorInputStream.java

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class LineIteratorInputStream {
    public static void main(String... args) {
        try {
            InputStream inputStream = new FileInputStream("D:\\Data\\data.txt");

            LineIterator lineIterator = IOUtils.lineIterator(inputStream, StandardCharsets.UTF_8);

            while(lineIterator.hasNext()) {
                String line = lineIterator.nextLine();
                System.out.println(line);
            }

            IOUtils.close(inputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
Simple Solution
Java Tutorials
Spring Boot Tutorials

Happy Coding 😊