简体   繁体   中英

JDK7 Files.copy

In the OpenJDK7 project java.nio.file.Files , there is the following function. My question is, should the while loop condition be >= instead of >? This is because the source.read javadoc says that when EOF is reached, it'll return -1 and not 0.

/**
 * Reads all bytes from an input stream and writes them to an output stream.
 */
private static long copy(InputStream source, OutputStream sink)
    throws IOException
{
    long nread = 0L;
    byte[] buf = new byte[BUFFER_SIZE];
    int n;
    while ((n = source.read(buf)) > 0) {
        sink.write(buf, 0, n);
        nread += n;
    }
    return nread;
}

You are looking at the wrong read function. The read function of InputStream that takes a byte array will return the number of bytes that have been copied into the buffer. So you can know how many bytes you can then copy out of it.

 * @return     the total number of bytes read into the buffer, or
 *             <code>-1</code> if there is no more data because the end of
 *             the stream has been reached.

So it does cover both cases: end of stream reached (-1) or no bytes read into the buffer for any other reason.

Whether this is a bug or not depends on the intent of the function.

Normally this will work exactly as you expect since the call to read will block until at least one byte of data becomes available. However, if the input stream is non-blocking, the read call will return 0 when there is currently no more data available. This state is different from the stream being actively closed.

In other words, one could argue that this is a bug or not, depending on what you expect it to do when faced with a non-blocking stream that has no data available at the moment the method is called.

Same, because InputStream.read(byte[]) here won't return 0. From javadoc

at least one byte is read

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM