Convert String to InputStream in Java

Learn to convert a String into InputStream using ByteArrayInputStream and IOUtils classes. Writing String to Steam is a frequent job in Java and having a couple of good shortcuts will prove useful.

For converting InputStream to String, read the linked article.

1. Using ByteArrayInputStream

Using ByteArrayInputStream is the simplest way to create InputStream from a String. Using this approach, we do not need any external dependency.

The string.getBytes() method encodes the String into a sequence of bytes using the platform’s default charset. To use a different charset, use the method getBytes​(Charset charset).

The StandardCharsets class provides the constant definitions for the standard charsets. For example, StandardCharsets.UTF_8.

String string = "howtodoinjava.com";

InputStream instream = new ByteArrayInputStream(string.getBytes());

2. Commons IO’s IOUtils

IOUtils is a very useful class for IO operations. This solution is also pretty good because apache commons is very much a mostly included jar in most applications.

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

IOUtils.toInputStream() makes code very much readable. It is an overloaded method so use the desired encoding while invoking this method.

static InputStream toInputStream(String input, Charset encoding)
static InputStream toInputStream(String input, String encoding)

Given program demonstrates how to create InputStream from a String.

String string = "howtodoinjava.com";

InputStream inStream = IOUtils.toInputStream(string, StandardCharsets.UTF_8);

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode