Welcome to Srini's blog

Wednesday, February 24, 2010

Keep one copy of InputStream -- JAVA

Due to restriction in java we can't keep InputSream as copy for further use. We can read stream only one time. There is a possibility to re-use input stream by converting it into string.
First convert the InputSream into string and use this string for multiple purposes. Whenever you want to re-use input stream convert string to stream and use it.

Procedure to convert InputStream into String:
Assume you have a InputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
String reqStr = sb.toString();


//Now If u want to use insput stream convert string to stream
inStream = new ByteArrayInputStream(reqStr.getBytes("UTF-8"));

1 comment:

  1. Thanks, I was looking for a solution like this!

    ReplyDelete