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
相关推荐
Seven974 分钟前
一致性Hash算法:如何实现分布式系统中的高效数据分片?
java
摇滚侠5 分钟前
IDEA 生成 try catch 快捷键
java·ide·intellij-idea
阿旭超级学得完1 小时前
C++11包装器(function和bind)
java·开发语言·c++·算法·哈希算法·散列表
掉鱼的猫2 小时前
Spring AI 2.0 GA 倒计时:先别急,来看看 Java AI 框架的另一条路
java·openai·agent
Refrain_zc2 小时前
Android 应用内 APK 安装全方案:从静默安装到普通安装的详解
java
正儿八经的少年2 小时前
Spring Boot 两种激活配置方式的作用与区别
java·spring boot·后端
云烟成雨TD2 小时前
Spring AI Alibaba 1.x 系列【52】Interrupts 中断机制:节点执行前后静态中断
java·人工智能·spring
疯狂成瘾者2 小时前
Spring Boot 项目中的 SMTP 邮件验证码服务技术解析
java·spring boot·后端
y = xⁿ3 小时前
Java并发八股学习日记
java·开发语言·学习