NIOCopy.java Source code

Java tutorial

Introduction

Here is the source code for NIOCopy.java

Source

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

public class NIOCopy {

    public static void main(String args[]) throws Exception {
        FileInputStream fIn;
        FileOutputStream fOut;
        FileChannel fIChan, fOChan;
        long fSize;
        MappedByteBuffer mBuf;

        fIn = new FileInputStream(args[0]);
        fOut = new FileOutputStream(args[1]);

        fIChan = fIn.getChannel();
        fOChan = fOut.getChannel();
        fSize = fIChan.size();

        mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize);
        fOChan.write(mBuf); // this copies the file
        fIChan.close();
        fIn.close();

        fOChan.close();
        fOut.close();
    }
}