Java – enter stream Read returns 0 or – 1?

What's the difference?

byte[] buffer = new byte[1024];
// this:
if (inputStream.read(buffer) > 0) { /*...*/ }
// and:
if (inputStream.read(buffer) != -1) { /*...*/ }

Can both determine the termination of network flow?

Solution

InputStream. JavaDocs of read () says:

In normal use, this will never happen, so it doesn't make much sense to test it explicitly (if you want to avoid forever looping, because in this case, the buffer is zero length and fast failure, just test the length of the buffer.)

Also, there are:

If you want to test the end of a file (or network flow, or other), use test:

if ( inputStream.read(buffer) != -1 ) ...

A non - buggy Java implementation never returns anything else to indicate that no more data is available

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>