Video in progress

Strong Middle 📁 IO and NIO

This code was supposed to copy a file, but the result file is empty. Where is the bug?

try (FileChannel in = FileChannel.open(src);
     FileChannel out = FileChannel.open(dst, CREATE, WRITE)) {
    ByteBuffer buf = ByteBuffer.allocate(8192);
    while (in.read(buf) != -1) {
        out.write(buf);
    }
}

buf.flip() is not called after reading from the channel. position stays at the end of the buffer and limit at capacity, so write sees "nothing to write". On top of that, clear() or compact() is also needed after writing.

📖 Answer

Let's trace the state. After the first read: position = 8192, limit = 8192. write writes from position to limit, that is, zero bytes. The next read returns 0 (not -1!) because the buffer has no room, and the loop spins forever.

The correct loop:

ByteBuffer buf = ByteBuffer.allocateDirect(64 * 1024);
while (in.read(buf) != -1 || buf.position() > 0) {
    buf.flip();          // read mode
    out.write(buf);      // may not write everything
    buf.compact();       // keep the unwritten remainder and get ready to write again
}

Why compact() and not clear(): if write didn't fully drain the buffer, clear() loses the remainder. For files this is rare, but on a socket channel it is a normal case.

The condition || buf.position() > 0 is there to finish writing the bytes left in the buffer after EOF.

Of course, for a simple file copy you don't need any of this: Files.copy(src, dst) or in.transferTo(0, in.size(), out) is enough. But this flip/compact loop shows up in network code every day.