JAVA 文件压缩(IO/NIO)

打印 上一主题 下一主题

主题 576|帖子 576|积分 1728

IO

  1. @GetMapping("io")
  2.   public void downloadZip() {
  3.     long start = System.currentTimeMillis();
  4.     EntityWrapper<AttachmentEntity> wrapper = new EntityWrapper<>();
  5.     List<AttachmentEntity> attachments = attachmentMapper.selectList(wrapper);
  6.     String zpiName = "D:/data/压缩文件io.zip";
  7.     try (FileOutputStream fos = new FileOutputStream(
  8.         zpiName); ZipOutputStream zipOutputStream = new ZipOutputStream(fos)) {
  9.       int i = 0;
  10.       for (AttachmentEntity attachment : attachments) {
  11.         String uuid = UUID.randomUUID().toString();
  12.         FileInputStream fileInputStream = new FileInputStream(attachment.getPath());
  13.         zipOutputStream.putNextEntry(new ZipEntry(uuid + "/" + attachment.getName()));
  14.         IOUtils.copy(fileInputStream, zipOutputStream);
  15.         zipOutputStream.closeEntry();
  16.         fileInputStream.close();
  17.         i++;
  18.       }
  19.     } catch (IOException e) {
  20.       e.printStackTrace();
  21.     }
  22.     long end = System.currentTimeMillis();
  23.     System.out.println("耗时:" + (end - start));
  24.   }
复制代码
NIO

  1. @GetMapping("nio")
  2.   public void downloadZipNio() throws FileNotFoundException {
  3.     long start = System.currentTimeMillis();
  4.     EntityWrapper<AttachmentEntity> wrapper = new EntityWrapper<>();
  5.     List<AttachmentEntity> attachments = attachmentMapper.selectList(wrapper);
  6.     String zpiName = "D:/data/压缩文件nio.zip";
  7.     try (FileOutputStream fos = new FileOutputStream(zpiName);
  8.         ZipOutputStream zos = new ZipOutputStream(fos);
  9.         WritableByteChannel wbc = Channels.newChannel(zos)) {
  10.       for (AttachmentEntity attachment : attachments) {
  11.         FileInputStream fis = new FileInputStream(attachment.getPath());
  12.         FileChannel channel = fis.getChannel();
  13.         String uuid = UUID.randomUUID().toString();
  14.         zos.putNextEntry(new ZipEntry(uuid + "/" + attachment.getName()));
  15.         channel.transferTo(0, channel.size(), wbc);
  16.       }
  17.     } catch (IOException e) {
  18.       e.printStackTrace();
  19.     }
  20.     long end = System.currentTimeMillis();
  21.     System.out.println("耗时:" + (end - start));
  22.   }
复制代码
运行时间对比(ms)

ionio375349350321340330
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

道家人

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表