Java中固定大小的文件压缩

Java中固定大小的文件压缩,java,zip,compression,Java,Zip,Compression,我想使用java.util库的zip包执行文件压缩。目的是将压缩文件限制为固定大小。如果压缩文件大小大于此限制,则应将其拆分为多个文件 try { fos = new FileOutputStream(p_request.getOutputFilePath() + zipFileName); ZipOutputStream zos = new ZipOutputStream(fos); zipEntry1 = new Zip

我想使用
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();

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

这意味着您必须:

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

但如果写入磁盘,则需要关闭流。我无法处理目录中的未来文件。zos.putNextEntry(zipEntry1);write(fileRAW,0,count);zos.close();currentSize+=zipEntry1.getCompressedSize();在关闭流之前,检查是否恢复了大小。如果没有,是的,你必须关闭它,然后再打开它。。。是的,很贵。或者,为什么不生成一个zip文件,然后拆分它呢?看看这个线程是否能帮助您@戴维德布罗萨德:可能吗?在预编辑之前,显示代码。已添加。请再次检查该问题。@user207421有任何提示吗?