快速读取流--文件复制

博客对文件读取方式进行测试,对比了一次读取一个1024长度数组和一个字节一个字节读取的性能。以约76M的121.rar文件为例,数组读取方式用时789ms,单个读取用时424s,建议采用数组读取方式,因其速度更快。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public static void main(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream("D:\\1upload\\121.rar");   
        FileOutputStream fos2 = new FileOutputStream("D:\\1upload\\213.rar");
        //方法二:  效率高,一次整个数组
        byte[] bytes = new byte[1024];
        int len = 0;
        long s2 = System.currentTimeMillis();
        while ((len = fis.read(bytes)) != -1) {
            fos2.write(bytes, 0, len);
        }
        long e2 = System.currentTimeMillis();
        System.out.println("一次读一个数组花费时间" + (e2-s2));
        fis.close();
        fos.close();
    }

测试结果:

一次读取一个1024长度的数组。

121.rar文件大概76M左右,采用数据的读取方式花费时间为789ms。

 

我们试下一个字节一个字节读试下:

public static void main(String[] args) throws Exception {
        System.out.println("流测试开始!!!!!");
        FileInputStream fis = new FileInputStream("D:\\1upload\\121.rar");  
        FileOutputStream fos = new FileOutputStream("D:\\1upload\\214.rar");
        int b = 0;
        long s1 = System.currentTimeMillis();
        while ((b = fis.read()) != -1) {
            fos.write(b);
        }
        long e1 = System.currentTimeMillis();
        System.out.println("一次读一个字节时间:"+ (e1 - s1));       
        fis.close();
        fos.close();
    }

测试结果:

测试结果大大的出乎意料,实在差距太大了,采用数组方式的只用了789ms 而单个读取的用了424s。

建议采用数组的读取方式,这种更快。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值