Pavle Jonoski
By Pavle Jonoski

How to convert String to InputStream in Java

How to convert String to InputStream in Java

Convert String to InputStream in Java

Very often, especially when writing tests, you need to pass an InputStream and

you want to read the data from a String.

To convert to input stream, the easiest way is first to convert the string to

array of bytes, then read from the bytes using ByteArrayInputStream.

Here is an one-liner on how to do that in Java:

1
2
3
4
5
6
7


InputStream stream = new ByteArrayInputStream("my-data".getBytes(StandardCharsets.UTF_8));