java copy file

   在Java编程中,复制文件的方法有很多,而且经常要用到。我以前一直是缓冲输入输出流来实现的(绝大多数人都是如此),近来在研究JDK文档时发现,用文件通道(FileChannel)来实现文件复制竟然比用老方法快了近三分之一。下面我就来介绍一下如何用文件通道来实现文件复制,以及在效率上的对比

一. 用文件通道的方式来进行文件复制

 /**
    * 使用文件通道的方式复制文件
    * 
    * @param s
    *            源文件
    * @param t
    *            复制到的新文件
    */
    public void fileChannelCopy(File s, File t) {
        FileInputStream fi = null;
        FileOutputStream fo = null;
        FileChannel in = null;
        FileChannel out = null;
        try {
            fi = new FileInputStream(s);
            fo = new FileOutputStream(t);
            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();
            }
        }
    }

与普通的缓冲输入输出流的复制效率的对比

普通的缓冲输入输出流代码:

测试代码:

输出结果:

由此可见,FileChannel复制文件的速度比BufferedInputStream/BufferedOutputStream复制文件的速度快了近三分之一。在复制大文件的时候更加体现出FileChannel的速度优势。而且FileChannel是多并发线程安全的。

原文:http://jingyan.baidu.com/article/ff4116259c2d7712e4823780.html

原文地址:https://www.cnblogs.com/vaer/p/4338050.html