JAVA 文件压缩(IO/NIO)

IO

java 复制代码
 @GetMapping("io")
  public void downloadZip() {
    long start = System.currentTimeMillis();
    EntityWrapper<AttachmentEntity> wrapper = new EntityWrapper<>();
    List<AttachmentEntity> attachments = attachmentMapper.selectList(wrapper);
    String zpiName = "D:/data/压缩文件io.zip";
    try (FileOutputStream fos = new FileOutputStream(
        zpiName); ZipOutputStream zipOutputStream = new ZipOutputStream(fos)) {
      int i = 0;
      for (AttachmentEntity attachment : attachments) {
        String uuid = UUID.randomUUID().toString();
        FileInputStream fileInputStream = new FileInputStream(attachment.getPath());
        zipOutputStream.putNextEntry(new ZipEntry(uuid + "/" + attachment.getName()));
        IOUtils.copy(fileInputStream, zipOutputStream);
        zipOutputStream.closeEntry();
        fileInputStream.close();
        i++;
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    long end = System.currentTimeMillis();
    System.out.println("耗时:" + (end - start));
  }

NIO

java 复制代码
@GetMapping("nio")
  public void downloadZipNio() throws FileNotFoundException {
    long start = System.currentTimeMillis();
    EntityWrapper<AttachmentEntity> wrapper = new EntityWrapper<>();
    List<AttachmentEntity> attachments = attachmentMapper.selectList(wrapper);
    String zpiName = "D:/data/压缩文件nio.zip";
    try (FileOutputStream fos = new FileOutputStream(zpiName); 
        ZipOutputStream zos = new ZipOutputStream(fos);
        WritableByteChannel wbc = Channels.newChannel(zos)) {
      for (AttachmentEntity attachment : attachments) {
        FileInputStream fis = new FileInputStream(attachment.getPath());
        FileChannel channel = fis.getChannel();
        String uuid = UUID.randomUUID().toString();
        zos.putNextEntry(new ZipEntry(uuid + "/" + attachment.getName()));
        channel.transferTo(0, channel.size(), wbc);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    long end = System.currentTimeMillis();
    System.out.println("耗时:" + (end - start));
  }

运行时间对比(ms)

io nio
375 349
350 321
340 330
相关推荐
南山十一少39 分钟前
Spring Security+JWT+Redis实现项目级前后端分离认证授权
java·spring·bootstrap
427724002 小时前
IDEA使用git不提示账号密码登录,而是输入token问题解决
java·git·intellij-idea
chengooooooo2 小时前
苍穹外卖day8 地址上传 用户下单 订单支付
java·服务器·数据库
李长渊哦3 小时前
常用的 JVM 参数:配置与优化指南
java·jvm
计算机小白一个3 小时前
蓝桥杯 Java B 组之设计 LRU 缓存
java·算法·蓝桥杯
南宫生5 小时前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
计算机毕设定制辅导-无忧学长6 小时前
Maven 基础环境搭建与配置(一)
java·maven
风与沙的较量丶7 小时前
Java中的局部变量和成员变量在内存中的位置
java·开发语言
m0_748251727 小时前
SpringBoot3 升级介绍
java
极客先躯8 小时前
说说高级java每日一道面试题-2025年2月13日-数据库篇-请说说 MySQL 数据库的锁 ?
java·数据库·mysql·数据库的锁·模式分·粒度分·属性分