Convert CharSequence to InputStream in Java using Apache Commons IO

Tags: InputStream CharSequence IOUtils Apache Commons Apache Commons IO

In this Java tutorial, we learn how to use the IOUtils utility class in Apache Commons IO library to convert a CharSequence 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 CharSequence into InputStream using IOUtils class

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

CharSequenceToInputStream.java

import org.apache.commons.io.IOUtils;

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

public class CharSequenceToInputStream {
    public static void main(String... args) {
        try {
            CharSequence charSequence = "Simple Solution";

            InputStream inputStream = IOUtils.toInputStream(charSequence, 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 😊