Java 大文件IO操作效率对比【我说说 你瞅瞅】

Java 文件IO操作效率对比

注:本文只做时间消耗层面对比,内存占用层面需要特别关注!

参数说明

文件总大小:2,111,993,850 字节(2.11 GB)

java 复制代码
static String defaultFilePath = "/tmp/data-24081412.json";

缓冲区大小:8192 字节

java 复制代码
static int defaultByteLength = 1024 * 8;

示例介绍

通过以下几种方式读取数据文件,并连续进行 10 次测试:

  1. FileInputStream + byte\[\] 文件字节输入流 + 字节数组读取方式
  2. FileInputStream + Scanner 文件字节输入流 + Scanner 读取方式
  3. FileReader + char\[\] 文件字符输入流 + 字符数组方式
  4. BufferedReader 缓冲字符流方式
  5. FileChannel 文件输入输出管道流「NIO」

比对结果

「5. FileChannel」 > 「1. FileInputStream + byte\[\]」> 「3. FileReader + char\[\]」>= 「4. BufferedReader」 > 「2. FileInputStream + Scanner」

注: 在操作文件时,会将文件区分为大文件、小文件、文本文件、二进制文件等,根据不同的文件需要选择合适的读取方式。通常大文件推荐使用 「FileChannel」效率会更高,小文件采用 IO 或 NIO 都可以,文本文件采用「BufferedReader」或者「FileChannel」判断换行符。

示例代码

4.1. FileInputStream + byte\[\] 文件字节输入流 + 字节数组读取方式

java 复制代码
/**
 * FileInputStream + byte[] 方式
 * 等同于 BufferedInputStream 字节输入缓冲流
 * 文件字节输入流 + 字节数组读取方式
 * 适用于:二进制文件或非文本文件
 */
public void testFileInputStreamWithBytes() {
    long startTime = new Date().getTime();
    // 使用 try 包装
    try (FileInputStream fileInputStream = new FileInputStream(defaultFilePath)){
        byte[] reads = new byte[defaultByteLength];
        int readCount;
        while ((readCount = fileInputStream.read(reads)) != -1) {
            // TODO 处理数据
        }
    } catch (IOException e) {
        System.out.printf("读取文件异常[ %s ]%n", e.getMessage());
    }

    System.out.printf("FileInputStream + byte[] 方式 读取文件共使用 %d 毫秒%n", new Date().getTime() - startTime);
}

10 次测试结果如下

java 复制代码
FileInputStream + byte[] 方式 读取文件共使用 884 毫秒
FileInputStream + byte[] 方式 读取文件共使用 331 毫秒
FileInputStream + byte[] 方式 读取文件共使用 319 毫秒
FileInputStream + byte[] 方式 读取文件共使用 420 毫秒
FileInputStream + byte[] 方式 读取文件共使用 333 毫秒
FileInputStream + byte[] 方式 读取文件共使用 321 毫秒
FileInputStream + byte[] 方式 读取文件共使用 327 毫秒
FileInputStream + byte[] 方式 读取文件共使用 339 毫秒
FileInputStream + byte[] 方式 读取文件共使用 328 毫秒
FileInputStream + byte[] 方式 读取文件共使用 398 毫秒

4.2. FileInputStream + Scanner 文件字节输入流 + Scanner 读取方式

java 复制代码
/**
 * FileInputStream + Scanner 方式
 * 文件字节输入流 + Scanner 读取文本方式
 * 适用于:文本文件
 */
public void testFileInputStreamWithScanner() {
    long startTime = new Date().getTime();
    // 使用 try 包装
    try (FileInputStream fileInputStream = new FileInputStream(defaultFilePath)){
        Scanner scanner = new Scanner(fileInputStream);
        while (scanner.hasNext()) {
            scanner.nextLine();
            // TODO 处理数据
        }
    } catch (IOException e) {
        System.out.printf("读取文件异常[ %s ]%n", e.getMessage());
    }

    System.out.printf("FileInputStream + Scanner 方式 读取文件共使用 %d 毫秒%n", new Date().getTime() - startTime);
}

10 次测试结果如下

java 复制代码
没有缓冲区,性能急剧下降!!
FileInputStream + Scanner 方式 读取文件共使用 16755 毫秒
FileInputStream + Scanner 方式 读取文件共使用 18744 毫秒
FileInputStream + Scanner 方式 读取文件共使用 17929 毫秒
FileInputStream + Scanner 方式 读取文件共使用 18640 毫秒
FileInputStream + Scanner 方式 读取文件共使用 18316 毫秒
FileInputStream + Scanner 方式 读取文件共使用 18015 毫秒
FileInputStream + Scanner 方式 读取文件共使用 18479 毫秒
FileInputStream + Scanner 方式 读取文件共使用 18755 毫秒
FileInputStream + Scanner 方式 读取文件共使用 18907 毫秒
FileInputStream + Scanner 方式 读取文件共使用 18783 毫秒

4.3. FileReader + char\[\] 文件字符输入流 + 字符数组方式

java 复制代码
/**
 * FileReader + char[] 方式
 * 等同于 BufferedReader 字符输入缓冲流
 * 文件字符输入流 + 字符数组方式
 * 适用于:字符文件
 */
public void testFileReaderWithChars() {
    long startTime = new Date().getTime();
    // 使用 try 包装
    try (FileReader fileReader = new FileReader(defaultFilePath)){
        char[] reads = new char[defaultByteLength];
        int readCount;
        while ((readCount = fileReader.read(reads)) != -1) {
            // TODO 处理数据
        }
    } catch (IOException e) {
        System.out.printf("读取文件异常[ %s ]%n", e.getMessage());
    }

    System.out.printf("FileReader + char[] 方式 读取文件共使用 %d 毫秒%n", new Date().getTime() - startTime);
}

10 次测试结果如下

java 复制代码
FileReader + char[] 方式 读取文件共使用 922 毫秒
FileReader + char[] 方式 读取文件共使用 971 毫秒
FileReader + char[] 方式 读取文件共使用 842 毫秒
FileReader + char[] 方式 读取文件共使用 985 毫秒
FileReader + char[] 方式 读取文件共使用 868 毫秒
FileReader + char[] 方式 读取文件共使用 1207 毫秒
FileReader + char[] 方式 读取文件共使用 1031 毫秒
FileReader + char[] 方式 读取文件共使用 981 毫秒
FileReader + char[] 方式 读取文件共使用 1259 毫秒
FileReader + char[] 方式 读取文件共使用 1034 毫秒

4.4. BufferedReader 缓冲字符流方式

java 复制代码
/**
 * BufferedReader 方式
 * 缓冲字符流方式
 * 适用于:字符文件
 */
public void testBufferedReader() {
    long startTime = new Date().getTime();
    // 使用 try 包装
    try (BufferedReader fileReader = new BufferedReader(new FileReader(defaultFilePath))){
        String line;
        while ((line = fileReader.readLine()) != null) {
            // TODO 处理数据
        }
    } catch (IOException e) {
        System.out.printf("读取文件异常[ %s ]%n", e.getMessage());
    }

    System.out.printf("BufferedReader 方式 读取文件共使用 %d 毫秒%n", new Date().getTime() - startTime);
}

10 次测试结果如下

java 复制代码
BufferedReader 方式 读取文件共使用 1870 毫秒
BufferedReader 方式 读取文件共使用 1895 毫秒
BufferedReader 方式 读取文件共使用 1890 毫秒
BufferedReader 方式 读取文件共使用 1875 毫秒
BufferedReader 方式 读取文件共使用 1829 毫秒
BufferedReader 方式 读取文件共使用 2060 毫秒
BufferedReader 方式 读取文件共使用 1821 毫秒
BufferedReader 方式 读取文件共使用 1944 毫秒
BufferedReader 方式 读取文件共使用 1902 毫秒
BufferedReader 方式 读取文件共使用 1860 毫秒

4.5. FileChannel 文件输入输出管道流「NIO」

java 复制代码
/**
 * FileChannel 方式
 * 文件输入输出管道流
 */
public void testFileChannel() {
    long startTime = new Date().getTime();
    // 使用 try 包装
    try (FileChannel channel = FileChannel.open(Paths.get(defaultFilePath), StandardOpenOption.READ)){
        // 构造B yteBuffer 有两个方法,ByteBuffer.allocate和 ByteBuffer.allocateDirect,两个方法都是相同入参,含义却不同。
        // ByteBuffer.allocate(capacity) 分配的是非直接缓冲区,非直接缓冲区的操作会在Java堆内存中进行,数据的读写会通过Java堆内存来传递。
        // ByteBuffer.allocateDirect(capacity) 分配的是直接缓冲区, 直接缓冲区的操作可以通过本地I/O传递,避免了在Java堆和本地堆之间的数据传输。
        ByteBuffer buf = ByteBuffer.allocate(defaultByteLength);
        while (channel.read(buf) != -1) {
            buf.flip();
            // TODO 处理数据
//                System.out.println(new String(buf.array()));
            buf.clear();
        }
    } catch (IOException e) {
        System.out.printf("读取文件异常[ %s ]%n", e.getMessage());
    }

    System.out.printf("FileChannel 方式 读取文件共使用 %d 毫秒%n", new Date().getTime() - startTime);
}

10 次测试结果如下

java 复制代码
FileChannel 方式 读取文件共使用 314 毫秒
FileChannel 方式 读取文件共使用 293 毫秒
FileChannel 方式 读取文件共使用 332 毫秒
FileChannel 方式 读取文件共使用 296 毫秒
FileChannel 方式 读取文件共使用 285 毫秒
FileChannel 方式 读取文件共使用 290 毫秒
FileChannel 方式 读取文件共使用 283 毫秒
FileChannel 方式 读取文件共使用 282 毫秒
FileChannel 方式 读取文件共使用 298 毫秒
FileChannel 方式 读取文件共使用 280 毫秒

结语

在 Java 8 中,「FileChannel」是处理文件 I/O 的高效方式,相比于传统的 I/O流「FileInputStream」、「FileOutputStream」等更加灵活方便且效率更高。

代码附录

java 复制代码
package com.demo.io;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Date;
import java.util.Scanner;

/**
 * 文件读取
 * @date 2024-08-14 16:42:21
 */
public class FileReadTest {

    // 文件路径
    static String defaultFilePath = "/Users/changbeibei/Desktop/work/wfilep.log-24081412";

    // 8k
    static int defaultByteLength = 1024 * 8;

    /**
     * FileInputStream + byte[] 方式
     * 等同于 BufferedInputStream 字节输入缓冲流
     * 文件字节输入流 + 字节数组读取方式
     * 适用于:二进制文件或非文本文件
     */
    @Test
    public void testFileInputStreamWithBytes() {
        long startTime = new Date().getTime();
        // 使用 try 包装
        try (FileInputStream fileInputStream = new FileInputStream(defaultFilePath)){
            byte[] reads = new byte[defaultByteLength];
            int readCount;
            while ((readCount = fileInputStream.read(reads)) != -1) {
                // TODO 处理数据
            }
        } catch (IOException e) {
            System.out.printf("读取文件异常[ %s ]%n", e.getMessage());
        }

        System.out.printf("FileInputStream + byte[] 方式 读取文件共使用 %d 毫秒%n", new Date().getTime() - startTime);
    }

    /**
     * FileInputStream + Scanner 方式
     * 文件字节输入流 + Scanner 读取文本方式
     * 适用于:文本文件
     */
    @Test
    public void testFileInputStreamWithScanner() {
        long startTime = new Date().getTime();
        // 使用 try 包装
        try (FileInputStream fileInputStream = new FileInputStream(defaultFilePath)){
            Scanner scanner = new Scanner(fileInputStream);
            while (scanner.hasNext()) {
                scanner.nextLine();
                // TODO 处理数据
            }
        } catch (IOException e) {
            System.out.printf("读取文件异常[ %s ]%n", e.getMessage());
        }

        System.out.printf("FileInputStream + Scanner 方式 读取文件共使用 %d 毫秒%n", new Date().getTime() - startTime);
    }

    /**
     * FileReader + char[] 方式
     * 等同于 BufferedReader 字符输入缓冲流
     * 文件字符输入流 + 字符数组方式
     * 适用于:字符文件
     */
    @Test
    public void testFileReaderWithChars() {
        long startTime = new Date().getTime();
        // 使用 try 包装
        try (FileReader fileReader = new FileReader(defaultFilePath)){
            char[] reads = new char[defaultByteLength];
            int readCount;
            while ((readCount = fileReader.read(reads)) != -1) {
                // TODO 处理数据
            }
        } catch (IOException e) {
            System.out.printf("读取文件异常[ %s ]%n", e.getMessage());
        }

        System.out.printf("FileReader + char[] 方式 读取文件共使用 %d 毫秒%n", new Date().getTime() - startTime);
    }

    /**
     * BufferedReader 方式
     * 缓冲字符流方式
     * 适用于:字符文件
     */
    @Test
    public void testBufferedReader() {
        long startTime = new Date().getTime();
        // 使用 try 包装
        try (BufferedReader fileReader = new BufferedReader(new FileReader(defaultFilePath))){
            String line;
            while ((line = fileReader.readLine()) != null) {
                // TODO 处理数据
            }
        } catch (IOException e) {
            System.out.printf("读取文件异常[ %s ]%n", e.getMessage());
        }

        System.out.printf("BufferedReader 方式 读取文件共使用 %d 毫秒%n", new Date().getTime() - startTime);
    }

    /**
     * FileChannel 方式
     * 文件输入输出管道流
     */
    @Test
    public void testFileChannel() {
        long startTime = new Date().getTime();
        // 使用 try 包装
        try (FileChannel channel = FileChannel.open(Paths.get(defaultFilePath), StandardOpenOption.READ)){
            // 构造B yteBuffer 有两个方法,ByteBuffer.allocate和 ByteBuffer.allocateDirect,两个方法都是相同入参,含义却不同。
            // ByteBuffer.allocate(capacity) 分配的是非直接缓冲区,非直接缓冲区的操作会在Java堆内存中进行,数据的读写会通过Java堆内存来传递。
            // ByteBuffer.allocateDirect(capacity) 分配的是直接缓冲区, 直接缓冲区的操作可以通过本地I/O传递,避免了在Java堆和本地堆之间的数据传输。
            ByteBuffer buf = ByteBuffer.allocate(defaultByteLength);
            while (channel.read(buf) != -1) {
                buf.flip();
                // TODO 处理数据
//                System.out.println(new String(buf.array()));
                buf.clear();
            }
        } catch (IOException e) {
            System.out.printf("读取文件异常[ %s ]%n", e.getMessage());
        }

        System.out.printf("FileChannel 方式 读取文件共使用 %d 毫秒%n", new Date().getTime() - startTime);
    }

    @Test
    public void testMain() {
        for (int i = 0; i < 10; i++) {
            System.out.printf("第 %d 次测试%n", i + 1);
            testFileInputStreamWithBytes();
            testFileInputStreamWithScanner();
            testFileReaderWithChars();
            testBufferedReader();
            testFileChannel();
        }
    }
}
相关推荐
SL_staff2 分钟前
从RBAC到场景化授权:《无忧·企业文档》三级权限模型的技术实践解析
java·开源·产品
传奇开心果编程1 小时前
【springboot基础语法学与练】第 1 课:从零开始
java·spring boot·后端·学习
SL_staff1 小时前
财务系统慎用低代码?从数据模型闭环看合规落地的技术实践
java·低代码·全栈
滕州市燕猫虎计算机科技工作室个体工商户1 小时前
IDEA:Command line is too long
java·ide·intellij-idea
步行cgn1 小时前
Spring p 命名空间注入详解
java·前端·spring
YatHinLay2 小时前
MyBatis 流式查询实战:ResultHandler 处理海量数据
java
天天被压力2 小时前
【跨市场数据实战 #08】可转债折价机会怎么筛:3个接口抓比价、列表和实时盘口
java·人工智能·python
张某布响丸辣3 小时前
附件下载的安全边界:路径白名单、NAS 哨兵文件与 Redis Lua 一次性令牌
java·redis·redis lua·nas哨兵
YatHinLay3 小时前
Spring Boot + Calcite 实现跨库查询
java
酷炫码神4 小时前
MosMos 创意效果与能力边界展示
java