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
相关推荐
guoruijun_2012_42 分钟前
fastadmin多个表crud连表操作步骤
android·java·开发语言
Hello-Brand13 分钟前
Java核心知识体系10-线程管理
java·高并发·多线程·并发·多线程模型·线程管理
乐悠小码18 分钟前
数据结构------队列(Java语言描述)
java·开发语言·数据结构·链表·队列
史努比.20 分钟前
Pod控制器
java·开发语言
2的n次方_23 分钟前
二维费用背包问题
java·算法·动态规划
皮皮林55123 分钟前
警惕!List.of() vs Arrays.asList():这些隐藏差异可能让你的代码崩溃!
java
莳光.23 分钟前
122、java的LambdaQueryWapper的条件拼接实现数据sql中and (column1 =1 or column1 is null)
java·mybatis
程序猿麦小七28 分钟前
基于springboot的景区网页设计与实现
java·spring boot·后端·旅游·景区
weisian15135 分钟前
认证鉴权框架SpringSecurity-2--重点组件和过滤器链篇
java·安全
蓝田~36 分钟前
SpringBoot-自定义注解,拦截器
java·spring boot·后端