IO操作学会使用缓冲区和流式复制

本文探讨了在Java中如何通过使用BufferedInputStream、BufferedOutputStream和FileChannel来提升文件IO操作的性能。测试结果显示,使用缓冲区和FileChannel的transfersTo方法能显著减少操作时间,尤其是在大型数据传输中。直接使用BufferedInputStream和BufferedOutputStream的字节操作由于方法调用频繁而较慢,而结合8KB缓冲区的两种方法表现相近,都在110毫秒左右。FileChannel的transferTo方法在某些系统上甚至可以实现DMA,避免CPU参与数据中转,进一步提高效率。

在进行文件 IO 处理的时候,使用合适的缓冲区可以明显提高性能

测试

    //使用BufferedInputStream和BufferedOutputStream
    private static void bufferedStreamByteOperation() throws IOException {
        try(BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(new File("")));
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File("")));){
            int i;
            while ((i = bufferedInputStream.read()) != -1) {
                bufferedOutputStream.write(i);
            }
        }
    }

    //额外使用一个8KB缓冲,再使用BufferedInputStream和BufferedOutputStream
    private static void bufferedStreamBufferOperation() throws IOException {
        try(BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(new File("")));
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File("")));){
            byte[] buffer = new byte[8192];
            int len = 0;
            while ((len = bufferedInputStream.read(buffer)) != -1) {
                bufferedOutputStream.write(buffer, 0, len);
            }
        }
    }
    //直接使用FileInputStream和FileOutputStream,再使用一个8KB的缓冲
    private static void largerBufferOperation() throws IOException {
        try(FileInputStream fileInputStream = new FileInputStream("");
            FileOutputStream fileOutputStream = new FileOutputStream("");){
            byte[] buffer = new byte[8192];
            int len = 0;
            while ((len = fileInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }
        }
    }

测试结果

1424649223 086% bufferedStreamByteOperation
117807808 007% bufferedStreamBufferOperation
112153174 007% largerBufferOperation

可以看到,第一种方式虽然使用了缓冲流,但逐字节的操作因为方法调用次数实在太多还是慢,耗时 1.4 秒;后面两种方式的性能差不多,耗时 110 毫秒左右。虽然第三种方式没有使用缓冲流,但使用了 8KB 大小的缓冲区,和缓冲流默认的缓冲区大小相同。

流式复制

对于类似的文件复制操作,如果希望有更高性能,可以使用FileChannel 的 transfreTo 方法进行流的复制。在一些操作系统(比如高版本的 Linux 和UNIX)上可以实现 DMA(直接内存访问),也就是数据从磁盘经过总线直接发送到目标文件,无需经过内存和 CPU 进行数据中转:

    private static void fileChannelOperation() throws IOException {
        FileChannel in = FileChannel.open(Paths.get("src.txt"), READ);
        FileChannel out = FileChannel.open(Paths.get("dest.txt"), CREATE, WRITE);
        in.transferTo(0, in.size(), out);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一只小小狗

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

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

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

打赏作者

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

抵扣说明:

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

余额充值