Convert String To InputStream In Java

This is simple exmaple for converting string object to a InputStream and then read it using the BufferedReader.

package javabeat.net.core;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class StringToInputStreamExample {
	public static void main(String[] args) throws IOException {
		String sampleString = "This is a example for String To InputStream";
	 
		// Convert String into InputStream using getBytes method
		InputStream is = new ByteArrayInputStream(sampleString.getBytes());
	 
		// Read using BufferedReader
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
	 
		String line;
		while ((line = br.readLine()) != null) {
			System.out.println(line);
		}
	 
		br.close();
	   }
}

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. Alex Dodu says:

    Great! Thanks.

Speak Your Mind

*