FileDocCategorySizeDatePackage
FileCopy3.javaAPI DocExample2128Sat Jan 24 10:44:28 GMT 2004je3.nio

FileCopy3

public class FileCopy3 extends Object

Fields Summary
Constructors Summary
Methods Summary
public static voidcopy(java.nio.channels.ReadableByteChannel in, java.nio.channels.WritableByteChannel out)

	// First, we need a buffer to hold blocks of copied bytes.
	ByteBuffer buffer = ByteBuffer.allocateDirect(32 * 1024);

	// Now loop until no more bytes to read and the buffer is empty
	while(in.read(buffer) != -1 || buffer.position() > 0) {
	    // The read() call leaves the buffer in "fill mode".  To prepare
	    // to write bytes from the bufferwe have to put it in "drain mode" 
	    // by flipping it: setting limit to position and position to zero
	    buffer.flip(); 

	    // Now write some or all of the bytes out to the output channel
	    out.write(buffer);

	    // Compact the buffer by discarding bytes that were written, 
	    // and shifting any remaining bytes.  This method also 
	    // prepares the buffer for the next call to read() by setting the
	    // position to the limit and the limit to the buffer capacity.
	    buffer.compact();
	}
    
public static voidmain(java.lang.String[] args)

	// Open file streams and get channels for them.
	ReadableByteChannel in = new FileInputStream(args[0]).getChannel();
	WritableByteChannel out;
	if (args.length > 1) out = new FileOutputStream(args[1]).getChannel();
	else out = Channels.newChannel(System.out);

	// Do the copy
	copy(in, out);
	
	// Exception handling and stream-closing code has been omitted.