How to convert a String to an InputStream in Java

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.

Convert a string to an InputStream using ByteArrayInputStream

The 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 an 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 the one below:

String str = "Hey, there!";

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

Convert a string to an InputStream using Apache Commons IO

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

String str = "Hey, there!";

// convert string to an 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.gradle file:

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

Further Reading

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

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.