Java Read List of Strings of InputStream using Apache Commons IO

Tags: String IOUtils Apache Commons Apache Commons IO InputStream FileInputStream

In this Java tutorial, we learn how to read a list of Strings of an InputStream object by using IOUtils utility class of Apache Commons IO library.

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 read list of Strings of an InputStream object using IOUtils class

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

Simple Solution
Java Tutorials
Apache Commons IO Tutorials

The Java program below, we use the IOUtils.readLines() method to read contents of the InputStream object of the above file and return a list of Strings. Then sprint the list of Strings to the standard output.

ReadLinesInputStream.java

import org.apache.commons.io.IOUtils;

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

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

            List<String> lines = IOUtils.readLines(inputStream, StandardCharsets.UTF_8);

            for(String line : lines) {
                System.out.println(line);
            }

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

Happy Coding 😊