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

导读:本篇文章讲解 IO流中通过字节流实现文件复制的四种方法,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

文件复制

我们试想生活中的文件复制步骤为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();

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/14643.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!