[ACCEPTED]-What 0 returned by InputStream.read() means? How to handle this?-inputstream
The only situation in which a InputStream
may return 10 0
from a call to read(byte[])
is when the byte[]
passed in 9 has a length of 0:
byte[] buf = new byte[0];
int read = in.read(buf); // read will contain 0
As specified by this part 8 of the JavaDoc:
If the length of b is zero, then 7 no bytes are read and 0 is returned
My guess: you 6 used available()
to see how big the buffer should be 5 and it returned 0
. Note that this is a misuse 4 of available()
. The JavaDoc explicitly states that:
It 3 is never correct to use the return value 2 of this method to allocate a buffer intended 1 to hold all data in this stream.
Take a look at the implementation of javax.sound.AudioInputStream#read(byte[] b, int 10 off, int len) ... yuck. They completely 9 violated the standard java.io.InputStream 8 semantics and return a read size of 0 if 7 you request fewer than a whole frame of 6 data.
So unfortunately; the common advice 5 (and api spec) should preclude having to 4 deal with return of zero when len > 0 but 3 even for JDK provided classes you can't 2 universally rely on this to be true for 1 InputStreams of arbitrary types.
Again, yuck.
According to Java API Doc:
http://java.sun.com/j2se/1.4.2/docs/api/java/io/InputStream.html#read(byte[])
It only can happen 6 if the byte[] you passed has zero items 5 (new byte[0]).
In other situations it must 4 return at least one byte. Or -1 if EOF reached. Or 3 an exception.
Of course: it depends of the actual implementation 2 of the InputStream you are using!!! (it 1 could be a wrong one)
I observed the same behavior (reading 0 3 bytes) when I build a swing console output 2 window and made a reader-thread for stdout 1 and stderr via the following code:
this.pi = new PipedInputStream();
po = new PipedOutputStream((PipedInputStream)pi);
System.setOut(new PrintStream(po, true));
When the 'main' swing application exits, and my console window is still open I read 0 from this.pi.read().
The read data was put on the console window resulting in a race condition some how, just ignoring the result and not updating the console window solved the issue.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.