views:

165

answers:

3

What 0 (number of bytes read) returned by InputStream.read means? How to handle this situation?

Update: I mean read(byte[] b) or read(byte[] b, int off, int len) methods which return number of bytes read.

+1  A: 

If you refer to the java.io.InputStream.read() method, it returns a byte

... as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned.

David Schmitt
+4  A: 

The only situation in which a InputStream may return 0 from a call to read(byte[]) is when the byte[] passed in has a length of 0:

 byte[] buf = new byte[0];
 int read = in.read(buf); // read will contain 0

As specified by this part of the JavaDoc:

If the length of b is zero, then no bytes are read and 0 is returned

My guess: you used available() to see how big the buffer should be and it returned 0. Note that this is a misuse of available(). The JavaDoc explicitly states that:

It is never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream.

Joachim Sauer
I agree:>This method blocks until input data is available, end of file is detected, or an exception is thrown.>If the length of b is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte.>If no byte is available because the stream is at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into b. Thanks!
Alexey Tigarev
+1  A: 

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 if the byte[] you passed has zero items (new byte[0]).

In other situations it must return at least one byte. Or -1 if EOF reached. Or an exception.

Of course: it depends of the actual implementation of the InputStream you are using!!! (it could be a wrong one)

helios