ToB企服应用市场:ToB评测及商务社交产业平台

标题: JAVA 文件压缩(IO/NIO) [打印本页]

作者: 道家人    时间: 2024-8-28 17:46
标题: JAVA 文件压缩(IO/NIO)
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企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4