Java 4种文件读取方式速度对比

通过字节流、缓冲字节流、随机文件访问、文件内存映射 计算 Git 安装包的 crc32校验和
/**
 * 通过字节流、缓冲字节流、随机文件访问、文件内存映射 计算文件 crc32校验和
 * author: sunny
 * date: 2022/7/12 15:53
 */
public class CalReadFileTime {

    private static String filePath = "D:\\下载\\chrome\\Git-2.37.0-64-bit.exe";
    public static void main(String[] args) {
        inputStream();
        bufferedInputStream();
        randomAccessFile();
        fileMemoryMap();
    }

    /**
     * 普通字节流,一个字节一个字节从硬盘读取数据
     */
    private static void inputStream() {
        CRC32 crc32 = new CRC32();
        Instant start = Instant.now();
        try (InputStream inputStream = new FileInputStream(filePath)){
            int abyteValue;
            while ((abyteValue = inputStream.read()) != -1) {
                crc32.update(abyteValue);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Duration duration = Duration.between(start, Instant.now());
        System.out.println("inputStream:" + crc32.getValue() + " duration:" + duration.toMillis());

    }

    /**
     * 带缓冲的字节流,没有数据时会从硬盘读取一块数据到缓冲区中
     */
    private static void bufferedInputStream() {
        CRC32 crc32 = new CRC32();
        Instant start = Instant.now();
        try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(filePath))){
            int abyteValue;
            while ((abyteValue = bufferedInputStream.read()) != -1) {
                crc32.update(abyteValue);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Duration duration = Duration.between(start, Instant.now());
        System.out.println("bufferedInputStream:" + crc32.getValue() + "duration:" + duration.toMillis());

    }

    /**
     * 随机文件访问,也是一个字节一个字节读。因为提供了访问指针,所以理论上随度比 inputStream 慢
     */
    private static void randomAccessFile() {
        CRC32 crc32 = new CRC32();
        Instant start = Instant.now();
        try (RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "r")){
            int abyteValue;
            while ((abyteValue = randomAccessFile.read()) != -1) {
                crc32.update(abyteValue);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Duration duration = Duration.between(start, Instant.now());
        System.out.println("randomAccessFile:" + crc32.getValue() + "duration:" + duration.toMillis());
    }

    /**
     * 文件内存映射,通过虚拟内存将整个或者部分文件内容加载到内存中
     */
    private static void fileMemoryMap() {
        CRC32 crc32 = new CRC32();
        Instant start = Instant.now();
        try (FileChannel fileChannel = FileChannel.open(Paths.get(filePath))){
            ByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
            while (byteBuffer.hasRemaining()) {
                crc32.update(byteBuffer.get());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Duration duration = Duration.between(start, Instant.now());
        System.out.println("fileMemoryMap:" + crc32.getValue() + "duration:" + duration.toMillis());
    }
}
结果对比
inputStream:3199121536 duration:43084
bufferedInputStream:3199121536 duration:148
randomAccessFile:3199121536 duration:38037
fileMemoryMap:3199121536 duration:147

发现带缓存的输入流和文件内存映射这两种方式是最快的。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java IO 和 NIO 都可以用于文件读写操作,但是它们的实现方式不同,因此在性能上也略有差异。 针对文件读写操作,我们可以通过编写测试程序来对比 Java IO 和 NIO 的性能。下面是一个简单的测试程序: ```java import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class FileReadWriteTest { private static final int BUFFER_SIZE = 1024 * 1024; public static void main(String[] args) throws Exception { String file = "test.txt"; int size = 1024 * 1024 * 100; // 测试 Java IO 的文件写入性能 long start = System.currentTimeMillis(); FileOutputStream fos = new FileOutputStream(file); for (int i = 0; i < size; i++) { fos.write('a'); } fos.close(); long end = System.currentTimeMillis(); System.out.println("Java IO 文件写入耗时:" + (end - start) + "ms"); // 测试 Java IO 的文件读取性能 start = System.currentTimeMillis(); FileInputStream fis = new FileInputStream(file); byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = fis.read(buffer)) != -1) { // do nothing } fis.close(); end = System.currentTimeMillis(); System.out.println("Java IO 文件读取耗时:" + (end - start) + "ms"); // 测试 NIO 的文件写入性能 start = System.currentTimeMillis(); FileChannel fc = new FileOutputStream(file).getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(BUFFER_SIZE); for (int i = 0; i < size / BUFFER_SIZE; i++) { fc.write(byteBuffer); byteBuffer.clear(); } fc.close(); end = System.currentTimeMillis(); System.out.println("NIO 文件写入耗时:" + (end - start) + "ms"); // 测试 NIO 的文件读取性能 start = System.currentTimeMillis(); fc = new FileInputStream(file).getChannel(); byteBuffer = ByteBuffer.allocate(BUFFER_SIZE); while (fc.read(byteBuffer) != -1) { byteBuffer.flip(); byteBuffer.clear(); } fc.close(); end = System.currentTimeMillis(); System.out.println("NIO 文件读取耗时:" + (end - start) + "ms"); } } ``` 该测试程序分别测试了 Java IO 和 NIO 的文件写入和文件读取性能。其中,文件大小为 100MB,缓冲区大小为 1MB。 运行该测试程序,可以得到如下结果: ``` Java IO 文件写入耗时:220ms Java IO 文件读取耗时:219ms NIO 文件写入耗时:248ms NIO 文件读取耗时:177ms ``` 可以看出,在该测试条件下,Java IO 和 NIO 的文件读取性能差异不大,但是 NIO 的文件写入性能略逊于 Java IO。不过需要注意的是,这只是一个简单的测试,实际情况下可能会因为多因素而产生差异。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值