Iain
Iain

Reputation: 10749

How do I convert a String to an InputStream in Java?

Given a string:

String exampleString = "example";

How do I convert it to an InputStream?

Upvotes: 1052

Views: 829653

Answers (5)

Anil Nivargi
Anil Nivargi

Reputation: 1717

There are two ways we can convert String to InputStream in Java,

  1. Using ByteArrayInputStream

Example :-

String str = "String contents";
InputStream is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
  1. Using Apache Commons IO

Example:-

String str = "String contents"
InputStream is = IOUtils.toInputStream(str, StandardCharsets.UTF_8);

Upvotes: 22

andreoss
andreoss

Reputation: 1800

You can try cactoos for that.

final InputStream input = new InputStreamOf("example");

The object is created with new and not a static method for a reason.

Upvotes: 1

Elijah
Elijah

Reputation: 13594

I find that using Apache Commons IO makes my life much easier.

String source = "This is the source of my input stream";
InputStream in = org.apache.commons.io.IOUtils.toInputStream(source, "UTF-8");

You may find that the library also offer many other shortcuts to commonly done tasks that you may be able to use in your project.

Upvotes: 295

Iain
Iain

Reputation: 10749

Like this:

InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8));

Note that this assumes that you want an InputStream that is a stream of bytes that represent your original string encoded as UTF-8.

For versions of Java less than 7, replace StandardCharsets.UTF_8 with "UTF-8".

Upvotes: 1653

A_M
A_M

Reputation: 7851

You could use a StringReader and convert the reader to an input stream using the solution in this other stackoverflow post.

Upvotes: 45

Related Questions