Tuesday, October 8, 2013

Re-reading Input streams in Java

There are certain cases, when you would want to re-read an InputStream rather than creating and closing it over and over again.

In a similar case, what you could do is, you can use the mark() and reset() methods provided in the JAVA API (http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html). You can invalidate the mark point by setting the read limit to -1, and then when you call reset it will reset the position to 0.

The mark should be called before the  InputStream is read, and the reset should be called after the InputStream in read.

Please refer the example below.

   InputStream is = <some input stream>;
   is.mark(-1); // invalidate mark point.

    String jsonBody = "";
    BufferedReader r = new BufferedReader(new      

    String line;
    try {
     while ((line = r.readLine()) != null) {
     jsonBody += line; //read the stream and build the JSON body
    } catch(Exception e) {
        try {
            is.reset(); //reset the input stream. This will bring the position of the input stream to 0.
            }catch (IOException e) {

No comments:

Post a Comment