import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

/**
 * Given an input filename and an output filename on the command line, 
 * copy the former's content to the latter using memory mapped IO.
 */
public class MappedOutput
{
    public static void main (String [] args)
        throws Exception
    {
        if (args.length < 2) {
            System.err.println ("Usage: inFilename outFilename");
            return;
        }

        String inFile = args[0];
	String outFile = args[1];
	FileChannel fc = null;
        MappedByteBuffer filedata = null;
        try {
            FileInputStream fis = new FileInputStream (inFile);
            fc = fis.getChannel();
            filedata =
                fc.map(MapMode.READ_ONLY, 0, fc.size());
        } catch (IOException e) {
            // file could not be opened; report problem
	    System.out.println("IO Exception");
	    return;
        } finally {
            fc.close();
        }

        FileOutputStream fos = new FileOutputStream (outFile);
        FileChannel out = fos.getChannel();

        // All the buffers have been prepared; write 'em out
        while (out.write (filedata) > 0) 
	{}
        out.close();
    }
}


