HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howjavainputstreamconvertstring

Problem

Given a string:

String exampleString = "example";


How do I convert it to an InputStream?

Solution

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

Code Snippets

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

Context

Stack Overflow Q#782178, score: 1664

Revisions (0)

No revisions yet.