IO流中通过字节流实现文件复制的四种方法

文件复制

我们试想生活中的文件复制步骤为Ctrl+C,Ctrl+V,通过这两个步解决问题,IO流完成复制的话也是两个步骤,首先用输入流来完成Ctrl+C,再用输出流完成Ctrl+V。输入流(源文件)每次读取一些信息,输出流在自己的文件里写入这些信息,输入流再读信息,输出流继续把读出的信息写进去,直到输出流读完信息,输入流就完成了信息写入,最终显示的就是文件复制,下面我们通过对一个视频文件进行复制,视频文件大小为14.4 MB (15,191,456 字节)。

方法一,基本字节流一次读写一个字节

耗时:太长

		File file = new File("D:\\vedio.mp4");
        FileInputStream in = new FileInputStream(file);
        FileOutputStream out = new FileOutputStream("D:\\vedio2.mp4");
        int len=0;
        while((len=in.read())!=-1){
            out.write(len);
            out.flush();
        }
        in.close();
        out.close();

方法二,基本字节流一次读写一个字节数组

耗时:422毫秒

File file = new File("D:\\vedio.mp4");
        FileInputStream in = new FileInputStream(file);
        FileOutputStream out = new FileOutputStream("D:\\vedio2.mp4");
        int len=0;
        byte[] bytes = new byte[1024 * 8];
        while((len=in.read(bytes))!=-1){
            out.write(bytes,0,len);
            out.flush();
        }
        in.close();
        out.close();

方法三,高效字节流一次读写一个字节

耗时:较长

File file = new File("D:\\vedio.mp4");
        BufferedInputStream bfi = new BufferedInputStream(new FileInputStream(file));
        BufferedOutputStream bfo = new BufferedOutputStream(new FileOutputStream(new File("D:\\vedio2.mp4")));
        int len=0;
        while((len=bfi.read())!=-1){
            bfo.write(len);
            bfo.flush();
        }
        bfo.close();
        bfi.close();

方法四,高效字节流一次读写一个字节数组

耗时:279毫秒

File file = new File("D:\\vedio.mp4");
        BufferedInputStream bfi = new BufferedInputStream(new FileInputStream(file));
        BufferedOutputStream bfo = new BufferedOutputStream(new FileOutputStream(new File("D:\\vedio2.mp4")));
        int len=0;
        byte[] bytes = new byte[1024 * 8];
        while((len=bfi.read(bytes))!=-1){
            bfo.write(bytes,0,len);
            bfo.flush();
        }
        bfo.close();
        bfi.close();
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值