文件复制的另一种选择,使用FileChannel复制文件

通常来说,FileChannel比普通的缓冲输入输出流有更高的效率
 
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
 
public class fileChannelCopy {
 
    public static void copy(File s, File d) {
        FileInputStream fi = null;
        FileOutputStream fo = null;
        FileChannel in = null;
        FileChannel out = null;
 
        try {
            fi = new FileInputStream(s);
            fo = new FileOutputStream(d);
            in = fi.getChannel();//得到对应的文件通道
            out = fo.getChannel();//得到对应的文件通道
            in.transferTo(0, in.size(), out);//连接两个通道,并且从in通道读取,然后写入out通道
 
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fi.close();
                in.close();
                fo.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    public static void main(String[] args) {
        File s = new File("e:\java.zip");
        File d = new File("d:\java.zip");
        new fileChannelCopy().copy(s,d);
        System.out.println("复制完成");
    }
}
原文地址:https://www.cnblogs.com/mybloging/p/6912925.html