package com.example.nio;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.Date;

/**
 * @author yuweijun 2016-10-31
 */
public class ChannelTransferExample {
    public static void main(String[] args) throws IOException {
        ClassLoader classLoader = ChannelTransferExample.class.getClassLoader();
        String fileName = classLoader.getResource("data/nio-from-file.txt").getFile();
        File fromFile = new File(fileName);
        RandomAccessFile randomAccessFile = new RandomAccessFile(fromFile, "rw");
        FileChannel fromChannel = randomAccessFile.getChannel();
        String toFileName = fromFile.getParent() + "/nio-to-file-" + new Date().getTime() + ".txt";
        System.out.println(toFileName);
        RandomAccessFile toFile = new RandomAccessFile(toFileName, "rw");
        FileChannel toChannel = toFile.getChannel();
        long position = 0;
        long count = fromChannel.size();
        toChannel.transferFrom(fromChannel, position, count);
    }
}
