Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

java - What 0 returned by InputStream.read() means? How to handle this?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...