How to convert String to InputStream in Java

In the previous tutorial, we discussed how can we convert an InputStream into a String. In this tutorial we are going to see the opposite direction. So, we are going to covert a String into an InputStream.

When you have a very big String that you want to process it incrementally, or a small portion of it at a time, converting it to an InputStream can be very helpful. In the previous tutorials what we actually did was to read the bytes from an input stream and append them to a String variable. In this tutorial we’re going to do the same technique.

Basically we are going to :

  • Get the bytes of the String
  • Create a new ByteArrayInputStream using the bytes of the String
  • Assign the ByteArrayInputStream object to an InputStream variable (which you can do as InputStream is a superclass of ByteArrayInputStream)

Here is the code:


import java.nio.charset.Charset;

public class StringToInputStream {

	public static void main(String[] args) throws IOException {

		String string = "This is a String.\nWe are going to convert it to InputStream.\n" +
				"Greetings from JavaCodeGeeks!";

		//use ByteArrayInputStream to get the bytes of the String and convert them to InputStream.
		InputStream inputStream = new ByteArrayInputStream(string.getBytes(Charset.forName("UTF-8")));

		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

		String output = bufferedReader.readLine();

		while (output != null) {
			output = bufferedReader.readLine();


This is a String. We are going to convert it to InputStream. Greetings from JavaCodeGeeks!

This was an example of how to convert String to InputStream in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Newest Most Voted
Inline Feedbacks
View all comments
4 years ago

InputStream inputStream = new ReaderInputStream(new StringReader(string))

Back to top button