文件copy

127 阅读1分钟

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

public class FileCopy {
    public void copyFileByChannel(File source, File dist) throws IOException {
        FileChannel sourceChannel = null;
        FileChannel targetChannel = null;
        try {
            sourceChannel = new FileInputStream(source).getChannel();
            targetChannel = new FileInputStream(dist).getChannel();

            for (long count = sourceChannel.size();count>0; ) {
                long transferred = sourceChannel.transferTo(sourceChannel.position(), count, targetChannel);
                count -= transferred;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (sourceChannel != null) {
                sourceChannel.close();
            }
            if (targetChannel!=null){
                targetChannel.close();
            }
        }
    }
}