【问题标题】:File Compression to fixed size In JavaJava中文件压缩到固定大小
【发布时间】:2019-10-31 17:44:10
【问题描述】:

我想使用java.util 库的zip 包执行文件压缩。目的是将压缩文件限制为固定大小。如果压缩后的文件大小超过此限制,则应将其拆分为多个文件。

try {
            fos = new FileOutputStream(p_request.getOutputFilePath() + zipFileName);
            ZipOutputStream zos = new ZipOutputStream(fos);
            zipEntry1 = new ZipEntry(f.getName());
            fis = new FileInputStream(f.getAbsolutePath());
            int count;
            while ((count = fis.read(fileRAW, 0, BUFFER)) != -1) {
              zipEntry1 = new ZipEntry(f.getName());
              if (currentSize >= (p_request.getMaxSizePerFileInMB() * 1024 * 1024)) {
                zipSplitCount++;
                zos.close();
                zos = new ZipOutputStream(new FileOutputStream(
                    p_request.getOutputFilePath() + zipFileName
                        + "_" + zipSplitCount + ".zip"));
                currentSize = 0;
              }
              zos.putNextEntry(zipEntry1);
//              zos.closeEntry();
              currentSize += zipEntry1.getCompressedSize();
              zos.write(fileRAW, 0, count);
            }

我总是将压缩大小设为 -1。有人可以为此建议一个干净的方法吗?

编辑:

所以我将文件压缩成固定大小的块,以获得与 f.1.zip、f.2.zip 相同的文件的多部分压缩 zip。现在解压后,有什么办法可以恢复原文件吗?目前,它说文件必须被破坏。

byte[] buffer = new byte[BUFFER];
        ZipInputStream zis = null;
        try {
          zis = new ZipInputStream(new FileInputStream(f.getAbsolutePath()));
          ZipEntry zipEntry = zis.getNextEntry();

          while(zipEntry!=null){

            String fileName = zipEntry.getName();
            File newFile = new File(p_request.getOutputFilePath() + fileName);

            System.out.println("file unzip : "+ newFile.getAbsoluteFile());

            new File(newFile.getParent()).mkdirs();

            FileOutputStream fos = new FileOutputStream(newFile);

            int len;
            while ((len = zis.read(buffer)) > 0) {
              fos.write(buffer, 0, len);
            }

            fos.close();
            zipEntry = zis.getNextEntry();
          }

          zis.closeEntry();
          zis.close();

【问题讨论】:

  • 重新编辑,显示代码。
  • 已添加。请再次检查问题。
  • @user207421 任何指针?

标签: java zip compression


【解决方案1】:

您得到 -1,因为在将 Zip 文件写入磁盘之前不知道大小。压缩发生在您保存整个 zip 文件时,而不是在您添加新条目时。

这意味着您必须:

  • 添加每个文件后将 zip 写入磁盘,然后测量 zip 以确定是继续添加还是创建新文件
  • 猜测大小基于平均压缩率和压缩前文件在磁盘上的大小。

【讨论】:

  • 但是如果我写入磁盘,我需要关闭流。我无法处理目录中的未来文件。 zos.putNextEntry(zipEntry1); zos.write(fileRAW, 0, count); zos.close(); currentSize += zipEntry1.getCompressedSize();
  • 在关闭流之前检查是否恢复了大小。如果不是,是的,您将不得不关闭它并再次打开它......是的,它很贵。或者,为什么不生成一个 zip 文件然后拆分它?
  • 看看这个帖子对你有没有帮助...stackoverflow.com/questions/3572430/…
  • @DavidBrossard 这可能吗?拆分拉链
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多