Home Tutorial Java Core Files Java convert string to InputStream

 
 

Share on Google+Share on Google+
Java convert string to InputStream
Posted on: June 10, 2006 at 12:00 AM
Advertisement
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
Advertisement

Related Tags for Java convert string to InputStream:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 10, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com