Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Effect on the original InputStream after wrapping with BufferedInputStream

Suppose I have a method that take in an InputStream.

This method need to wrap this InputStream with a BufferedInputStream to use its mark and reset functionality. However, the passed in InputStream might still be used by the caller of the method.

public static void foo(InputStream is) throws Exception {
    BufferedInputStream bis = new BufferedInputStream(is);
    int b = bis.read();
}

public static void main(String[] args) {


    try {
        InputStream is = new FileInputStream(someFile);
        foo(is);
        int b = is.read(); // return -1
    }catch (Exception e) {
        e.printStackTrace();
    }
}

My questions is: what exactly happen to the original InputStream when the BufferedInputStream is read (or initialized)?

My assumption is that the original InputStream will also move forward if the BufferedInputStream is read. However, after debugging my code, I have found that the InputStream will return -1 instead when read.

If the original InputStream is not readable after such process, how should I go about achieving my purpose:

InputStream is;
foo(is);               // Method only take in generic InputStream object
                       // Processing of the passed in InputStream object require mark and reset functionality
int b = is.read();     // Return the next byte after the last byte that is read by foo()

EDIT: I suppose what I'm asking for is quite generic and therefore requires a lot of work. As for what I'm working on, I actually don't need the full mark & reset capability so I have found a small work around. However, I will leave the 2nd part of the question here, so feel free to attempt this problem :).

like image 915
Zekareisoujin Avatar asked Nov 11 '22 14:11

Zekareisoujin


1 Answers

The default bufferSize of a BufferedInputStream is 8192, so when you're reading from BufferedInputStream, it tries to fill it's buffer. So, if you have to read from your InputStream less bytes, than the bufferSize, then the full content of your InputStream is read to the buffer, therefore you're getting -1 after reading from BufferedInputStream

Have a look at the BufferedInputStream source code: http://www.docjar.com/html/api/java/io/BufferedInputStream.java.html

like image 130
Alexander Tokarev Avatar answered Nov 14 '22 22:11

Alexander Tokarev