第8章-第4节-Java中字节流的缓冲流

本文详细介绍了Java中的缓冲流如何通过在内存中设置缓冲区来提高文件读写效率,包括BufferedInputStream和BufferedOutputStream的创建,以及在实际案例中的应用,如视频文件复制。
摘要由CSDN通过智能技术生成

1、缓冲流:属于高级IO流,并不能直接读写数据,需要依赖于基础流。缓冲流的目的是为了提高文件的读写效率?那么是如何提高文件的读写效率的呢?

在内存中设置一个缓冲区,缓冲区的默认大小是8192字节(8K),从文件中读取的内容,先存储到缓冲区,当缓冲区内容填充满了之后,才会将缓冲区的内容通过输出流写出到文件,这样,就减少了文件之间的传输次数,从而提高了文件的读写效率

2、缓冲字节输入流/缓冲字节输出流(读入与写出)

方法名说明
BufferedOutputStream(OutputStream out)创建字节缓冲输出流对象
BufferedInputStream(InputStream in)创建字节缓冲输入流对象

1)、案例:

        // 创建一个字节缓冲输入流
		BufferedInputStream bis =
                new BufferedInputStream(new FileInputStream("day16_io\\01.jpg"));
        // 创建一个字节缓冲输出流
        BufferedOutputStream bos =
                new BufferedOutputStream(new FileOutputStream("day16_io\\02.jpg"));

        long start = System.currentTimeMillis();
        // 2. 具体的读写操作
        byte[] bs = new byte[1024];
        int len = bis.read(bs);
        while(len != -1){
            bos.write(bs, 0, len);
            len = bis.read(bs);
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);

        // 3. 关闭资源
        bis.close();
        bos.close();

 2)、练习复制视频文件

    public static void main(String[] args) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        /**
         * 缓冲流
         */
        try {
            bis =new BufferedInputStream(new FileInputStream("D://hecheng.mp4"));

            bos =new BufferedOutputStream(new FileOutputStream("D://"+ UUID.randomUUID()+".mp4"));

            //1. 记录起始时间点
            long start = System.currentTimeMillis();

            byte [] nums = new byte[1024];
            int len = -1;
            while((len = bis.read(nums)) != -1){
                bos.write(nums,0,len);
            }

            //2. 记录终点毫秒数
            long end = System.currentTimeMillis();

            System.out.println("复制成功!时间长:"+(end-start));


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }

    }

3、字节流总结:

 

 关于字节缓冲流,还可以看看我这篇博客:Java下字节缓冲流的读入和写出

本电子书目录: 《Java基础的重点知识点全集》

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zwarwolf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值