Search code examples
javaiostreaminputstream

Java IO difference in reading streams


Could you help me figure out the streams. Why in the tutorials I find that when reading from a file, we use len != -1 (for example).And when reading from a stream and then writing to a stream, we use len> 0.What is the difference when reading?

PS The codes below are taken from examples

byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
    out.write(buffer, 0, len);
}
 byte[] buf = new byte[8192];
    int length;
    while ((length = source.read(buf)) > 0) {
        target.write(buf, 0, length);
    }
}

UPD

link1

link2

link3

UPD 2

You can also look at IOUtils.copy and Files.copy They are different too

UPD 3

I read that the read method does not return 0, or the available number of bytes, or -1. Thanks everyone


Solution

  • There is no difference. The javadoc for InputStream.read(byte[]) says the following:

    If the length of [the buffer] 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.

    and

    Returns the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.

    A careful reading of the above tells us that read will only ever return zero if the buffer size is zero.

    The buffer size is not zero in your two examples. Therefore len != -1 and length > 0 will have the same effect.