java高效的文件复制方法




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

        /**

        * 使用文件通道的方式复制文件

        * 

        * @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();

                }

            }

        }

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

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

  2. public class NormalCopy {
    /**
    * @param s
    * @param t
    * @desc: 复制文件2个步骤:
    * 1.将源文件和目标文件分别放到输入流和输出流中。
    * 2.进行流操作即可。
    * File s --> FileInputStream fi
    *   File t --> FileOutputStream fo
    *   读写操作。
    */
    public void copy(File s, File t) {


    InputStream fis = null;
    OutputStream fos = null;
    try {
    fis = new BufferedInputStream(new FileInputStream(s));
    fos = new BufferedOutputStream(new FileOutputStream(t));
    byte[] buf = new byte[2048];
    int i;
    while ((i = fis.read(buf)) != -1) {
    fos.write(buf, 0, i);
    }
    } catch (Exception e) {
    e.printStackTrace();
    }finally{
    try{
    fis.close();
    fos.close();
    }catch(IOException e){
    e.printStackTrace();
    }
    }
    }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值