# How to convert a String to an InputStream in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Dec 8, 2019, updated Oct 29, 2022. Topics: Java.
Canonical URL: https://attacomsian.com/blog/java-convert-string-to-inputstream

> A quick article to learn how to convert a string into an InputStream object in Java.

In my [previous article](https://attacomsian.com/blog/java-convert-inputstream-to-string), 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 &mdash; 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:

```java
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:

```java
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](https://commons.apache.org/proper/commons-io/) library provides the `IOUtils.toInputStream()` method to easily convert a string into an instance of `InputStream` as shown below:

```java
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:

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

For a [Gradle project](https://attacomsian.com/blog/install-gradle-on-ubuntu), add the following dependency to your `build.gradle` file:

```groovy
implementation 'commons-io:commons-io:2.6'
```

## Further Reading

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

* [Reading and Writing Files in Java](https://attacomsian.com/blog/java-read-write-files)
* [How to Read and Write Text Files in Java](https://attacomsian.com/blog/java-read-write-text-files)
* [How to Read and Write Binary Files in Java](https://attacomsian.com/blog/java-read-write-binary-files)
* [Reading and Writing Files using Java NIO API](https://attacomsian.com/blog/java-read-write-files-nio-api)
* [How to read a file line by line in Java](https://attacomsian.com/blog/how-to-read-a-file-line-by-line-in-java)
