Convert String to InputStream in Java

In this post we will provide an example of how to convert a String to InputStream in Java.

Convert String to InputStream in Java

The following example uses the standard JDK libraries.

The example above convert the String to an InputStream. This is done using the ByteArrayInputStream which is a subclass of InputStream. The input stream is then read back to a String using the BufferedReader and InputStreamReader.

Running the above code produces the following output

The second example uses the apache commons io library which makes the process a lot simpler. You will first need to add the following dependency

As you can see from the example above, using the apache-commons-io library makes it a lot simpler. The IOUtils class has two convenience methods:

  • IOUtils.toInputStream(): This converts your String to an InputStream
  • IOUtils.readLines(): This converts your InputStream into a String.

Running the above code produces the following output:

Similar posts:

  1. Convert ByteArray to String
  2. How to split a string
  3. Convert a string to a list split by new line
  4. How to read a file in Java

References:

  1. InputStream API Documentation

Leave a Reply