Convert String to InputStream in Java using Apache Commons IO

Tags: Convert String IOUtils Apache Commons Apache Commons IO InputStream

In this Java tutorial, we learn how to use the IOUtils utility class in Apache Commons IO library to convert a String object to an InputStream object.

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 convert String into InputStream using IOUtils class

The Java program below, we convert a String object into InputStream using the IOUtils.toInputStream() method and then print the InputStream to the standard output.

StringToInputStream.java

import org.apache.commons.io.IOUtils;

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

public class StringToInputStream {
    public static void main(String... args) {
        try {
            String value = "Simple Solution";

            InputStream inputStream = IOUtils.toInputStream(value, StandardCharsets.UTF_8);

            int data;
            while ((data = inputStream.read()) != IOUtils.EOF) {
                System.out.print((char)data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
Simple Solution

Happy Coding 😊