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
相关推荐
purrrew7 分钟前
【Java ee初阶】初始网络
java·网络
程序员Bears11 分钟前
从零打造个人博客静态页面与TodoList应用:前端开发实战指南
java·javascript·css·html5
Helibo4429 分钟前
GESPC++六级复习
java·数据结构·算法
柒七爱吃麻辣烫1 小时前
在Linux中安装JDK并且搭建Java环境
java·linux·开发语言
极小狐2 小时前
极狐GitLab 容器镜像仓库功能介绍
java·前端·数据库·npm·gitlab
努力的搬砖人.2 小时前
如何让rabbitmq保存服务断开重连?保证高可用?
java·分布式·rabbitmq
_星辰大海乀2 小时前
数据库约束
java·数据结构·数据库·sql·链表
多多*2 小时前
Java反射 八股版
java·开发语言·hive·python·sql·log4j·mybatis
码农飞哥2 小时前
互联网大厂Java面试实战:Spring Boot到微服务的技术问答解析
java·数据库·spring boot·缓存·微服务·消息队列·面试技巧
liudongyang1233 小时前
jenkins 启动报错
java·运维·jenkins