Nov 7, 2018

Copy File Example Using Memory Mapped file in Java

See also: 

Read File Example Using Memory Mapped file in Java

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

public class Main {

    public File copy(File source) throws IOException {
        FileChannel in = null;
        FileChannel out = null;

        File dest = new File("i88.ca.copy.txt");

        try {
            in = new FileInputStream(source).getChannel();
            out = new FileOutputStream(dest).getChannel();

            long size = in.size();
            MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);

            out.write(buf);

        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }

        return dest;
    }

    public static void main(String[] args) throws IOException {

        File s;
        s = new Main().copy(new File("i88.ca.txt"));
        System.out.println(s);
    }
}