File Copying with Buffers

Example 6-4 is another file copying program. Instead of using the shortcut FileChannel.transferTo( ) method, this example defines a generic copy( ) method for copying bytes from one channel to another and demonstrates the basic java.nio I/O loop, described here:

  1. The buffer is filled with bytes from one channel.

  2. The buffer is flipped, making it ready to be drained. See Buffer and Buffer.flip( ) for details.

  3. The buffer is drained by writing bytes from it to another channel.

  4. The buffer is compacted, discarding bytes that have been drained from it and shifting remaining bytes to the beginning of the buffer. As part of this process, the current position of the buffer is reset to point to the first available byte in the buffer, making the buffer ready to be filled again. See ByteBuffer.compact( ) for details. If the call to write( ) completely drained the buffer, then clear( ) can be used instead of compact( ).

This loop continues until the input channel indicates that there are no more bytes to read (its read( ) method returns -1) and the buffer is empty.

Variants on this basic loop appear in most programs that use the New I/O API, so it is important to understand it. For clarity, Example 6-4 omits exception-handling and stream-closing code so that you can focus on the basic loop.

Example 6-4. FileCopy3.java

package je3.nio; import java.io.*; import java.nio.*; import java.nio.channels.*; public class FileCopy3 { public static void main(String[ ] args) throws IOException ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.