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
相关推荐
好大哥呀22 分钟前
Java Web的学习路径
java·前端·学习
f***147724 分钟前
SpringBoot实战:高效实现API限流策略
java·spring boot·后端
on the way 12325 分钟前
day06-SpringDI 依赖注入
java·spring
C***11501 小时前
Spring aop 五种通知类型
java·前端·spring
BD_Marathon1 小时前
SpringBoot——多环境开发配置
java·spring boot·后端
代码N年归来仍是新手村成员2 小时前
【Java转Go】即时通信系统代码分析(一)基础Server 构建
java·开发语言·golang
关于不上作者榜就原神启动那件事2 小时前
Java中大量数据Excel导入导出的实现方案
java·开发语言·excel
Coder_Boy_3 小时前
基于SpringAI的在线考试系统设计总案-知识点管理模块详细设计
android·java·javascript
Assby3 小时前
如何尽可能精确计算线程池执行 shutdown() 后的耗时?
java·后端
焰火19993 小时前
[Java]自定义重试工具类
java