Friday, 14th October 2011
Follow WikiJava on twitter now. @Wikijava

How to convert String in InputStream and back

From WikiJava

Jump to: navigation, search
The author suggests:

buy this book

This article shows how to convert a java.lang.String into a java.lang.InputStream. This comes very useful when in general you are trying to use methods that need as parameter an InputStream.


Contents

Convert from a String to an InputStream

ByteArrayInputStream inputStream = new 
             ByteArrayInputStream(original.getBytes());

Convert from an InputStream to a String

Unfortunately this is slightly more complex, but in the end nothing too critical. Basically The conversion from inputStream to String consists in reading the inputStream and saving it's content in a String. In this example I used a StringBuffer, to speed up the creation of the String.

StringBuffer buffer = new StringBuffer();
byte[] b = new byte[4096];
try {
	for (int n; (n = inputStream.read(b)) != -1;) {
		buffer.append(new String(b, 0, n));
	}
} catch (IOException e) {
	e.printStackTrace();
}
String result = buffer.toString();


Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page


Comments on wikijava are disabled now, cause excessive spam.