Java convert string to InputStream


 

Java convert string to InputStream

In this section, you will learn how to convert string to Inputstream.

In this section, you will learn how to convert string to Inputstream.

Java convert string to InputStream

In this section, you will learn how to convert string to Inputstream.

In one of the previous sections, we have discussed the conversion of InputStream to string. Here we are going to do just reverse of it. You can easily convert a string into an input stream.

You can see in the given example, we have specified a string and to convert this string into InputStream, we have used ByteArrayInputStream class. The constructor of this class takes the string byte array  using the getBytes() method. Then we have used the BufferedReader class to read and display the converted InputStream.

Here is the code:

import java.io.*;
import java.io.InputStream;

public class ConvertStringToInputStream {
	public static void main(String[] args) throws Exception {
		String text = "Hello world";
		InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String line;
		while ((line = br.readLine()) != null) {
			System.out.println(line);
		}

		br.close();

	}
}

You can convert the string into InputStream by using the following code:

InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));

Output:

Hello world

Ads