Java 字节缓冲流

文章分析了Java中四种文件操作方法,包括基本字节流和缓冲字节流,发现使用缓冲字节流一次读写一个字节数组的方法(method4)在文件复制时具有最高效率。
摘要由CSDN通过智能技术生成

 字节缓冲流

import java.io.*;

//把 E:\\itcast\\字节流复制图片.avi 复制到目录下的 字节流复制图片.avi
public class Demo {
    public static void main(String[] args) throws IOException {
        long startTime = System.currentTimeMillis();

//        method1();//共耗时:37851毫秒
//        method2();//共耗时:121毫秒
//        method3();//共耗时:325毫秒
        method4();//共耗时:20毫秒

        long endTime = System.currentTimeMillis();
        System.out.println("共耗时:"+(endTime-startTime)+"毫秒");

    }
    //method1:基本字节流一次读写一个字节
    public static void method1() throws IOException {
        //E:\\itcast\\字节流复制图片.avi
        //字节流复制图片.avi
        FileInputStream fis = new FileInputStream("E:\\itcast\\字节流复制图片.avi");
        FileOutputStream fos = new FileOutputStream("myByteStream\\字节流复制图片.avi");
        int by;
        while ((by = fis.read())!= -1) {
            fos.write(by);
        }
        fos.close();
        fis.close();
    } 
    //method2:基本字节流一次读写一个字节数组
    public static void method2() throws IOException {
        //E:\\itcast\\字节流复制图片.avi
        //字节流复制图片.avi
        FileInputStream fis = new FileInputStream("E:\\itcast\\字节流复制图片.avi");
        FileOutputStream fos = new FileOutputStream("myByteStream\\字节流复制图片.avi");
        byte [] bytes = new byte[1024];
        int len;
        while((len = fis.read(bytes))!= -1) {
            fos.write(bytes,0,len);
        }
        fos.close();
        fis.close();
    }
    //method3:缓冲字节流一次读写一个字节
    public static void method3() throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myByteStream\\字节流复制图片.avi"));
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\itcast\\字节流复制图片.avi"));

        int by;
        while((by = bis.read())!= -1) {
            bos.write(by);
        }
        bos.close();
        bis.close();
    }
    //method4:缓冲字节流一次读写一个字节数组
    public static void method4() throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myByteStream\\字节流复制图片.avi"));
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\itcast\\字节流复制图片.avi"));

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

        字节缓冲流能够提高传输效率,经过代码测试,通过缓冲字节流一次读写一个字节数组的方法效率最高。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值