IO缓冲流

本文探讨了使用缓冲数组与高级流(如BufferedInputStream和BufferedOutputStream)进行文件复制的高效方式,对比了两者在速度和内存管理上的优势,并介绍了flush操作的作用。
摘要由CSDN通过智能技术生成
  1. 定义缓冲数组进行文件复制
public class CopyDemo1 {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("Kalimba/.mp3");
        FileOutputStream fos = new FileOutputStream("Kaliba2.mp3");

        //创建一个10k的缓存
        byte[] data = new byte[1024*10];
        int len;
        long s = System.currentTimeMillis();
        while ((len=fis.read(data))!=-1){
            fos.write(data,0,len);
        }
        long e = System.currentTimeMillis();
        System.out.println("over"+(e-s));
        fis.close();
        fos.close();

    }
}
  1. 使用缓冲流无需定义数组,加快效率
    在这里插入图片描述
    高级流需要依赖低级流,低级流就相当于一根什么的输液管,高级流就是输液管上的卡子,有其他功能所以高级。
public class CopyDemo2 {
    public static void main(String[] args) throws IOException {
        //高级流不能直接指向文件,它创建时需要低级流对象
        FileInputStream fis = new FileInputStream("Ka.mp3");  //低级流指向对象
        BufferedInputStream bis = new BufferedInputStream(fis);

        FileOutputStream fos = new FileOutputStream("Ka.mp3");
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        int d;

        long s = System.currentTimeMillis();
        while((d=bis.read())!=-1){
            bos.write(d);
        }
        long e = System.currentTimeMillis();
        System.out.println("over"+(e-s));

        bis.close();
        bos.close();//只关高级流,低级流联动自动关
    }
}

void flush();
强制将当前缓冲区中的字节一次性写出
同时清空缓冲区,是即时的写出
实际上也会增加写出的次数,降低写出效率
调用close前会自动调用flush,所以flush调用不必须。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值