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

Iain picture Iain · Apr 23, 2009 · Viewed 680.4k times · Source

Given a string:

String exampleString = "example";

How do I convert it to an InputStream?

Answer

Iain picture Iain · Apr 23, 2009

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".