I am reading a book 'Java Network Programming (Elliotte Rusty Harold)'. And I met the following sentence, after this code.
FileInputStream fin = new FileInputStream("data.txt");
BufferedInputStream bin = new BufferedInputStream(fin);
...intermixing calls to different streams connected to the same source may violate several implicit contracts of the filter streams.
And the following code came out.
InputStream in = new FileInputStream("data.txt");
in = new BufferedInputStream(in);
I understand that this simplifies the syntax, but I wonder what 'several implicit contracts of the filter streams' means.
If multiple filter streams are connected to the same source stream, then those filter streams may behave in incompatible ways. Imagine, as a hypothetical, two streams:
Now imagine running the following code:
InputStream in = new FileInputStream("data.txt");
BufferedInputStream buf = new BufferedInputStream(in);
NoChangeInputStream nop = new NoChangeInputStream(in);
int byte0 = buf.read();
int byte1 = nop.read();
You would expect that byte1
contains the second byte of the file, but this is incorrect. The BufferedInputStream
consumed much more than one byte, when it first filled its buffer, and hence one's typical implicit assumptions about how streams ought to behave, are violated.
This is not the only example by far--consider as well a case where two distinct buffered input streams are consuming the same input file--it's not clear which of the two buffers will get any particular byte, even though the order in which you read from the buffers is clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With