In my previous article, I wrote about different ways to convert an instance of InputStream to a string in Java. In this article, we will look at different ways to do the opposite — convert a string back into an InputStream object.

Using ByteArrayInputStream Class

The simplest and most straightforward way to convert a string into an InputStream object is to use ByteArrayInputStream as shown below:

String str = "Hey, there!";

// convert string to input stream
InputStream stream = new ByteArrayInputStream(str.getBytes());

By default, getBytes() encodes the string using the default character encoding of the operating system. However, you can overwrite it by passing an encoding scheme of your choice like below:

String str = "Hey, there!";

// convert string to input stream
InputStream stream = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));

Using Apache Commons IO

The Apache Commons IO library provides IOUtils.toInputStream() method to easily convert a string into an instance of InputStream as shown below:

String str = "Hey, there!";

// convert string to input stream
InputStream stream = IOUtils.toInputStream(str, StandardCharsets.UTF_8);

Don't forget to include Apache Commons IO dependency to your Maven's project pom.xml file:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

For a Gradle project, add the following dependency to your build.gralde file:

implementation 'commons-io:commons-io:2.6'

Further Reading

You may be interested in other Java I/O articles:

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Buy me a coffee (cost $3)

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.