Java - 压缩现有文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14350629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:58:22  来源:igfitidea点击:

Java - Zipping existing files

javazipappendtruezip

提问by Michael 'Maik' Ardan

Possible Duplicate:
Appending files to a zip file with Java

可能的重复:
使用 Java 将文件附加到 zip 文件

Hello Java Developers,

您好 Java 开发人员,

Here's the scenario:

Say I have a textfile named sample.txt. What I actually want to do is to put the sample.txtfile into a *.zipfile named TextFiles.zip.

Here's what I have learned so far.

这是场景:

假设我有一个名为sample.txt. 我真正想做的是将sample.txt文件放入*.zip名为TextFiles.zip.

这是我到目前为止所学到的。

try{
    File f = new File(compProperty.getZIP_OUTPUT_PATH());
    zipOut = new ZipOutputStream(new FileOutputStream(f));
    ZipEntry zipEntry = new ZipEntry("sample.txt");
    zipOut.putNextEntry(zipEntry);
    zipOut.closeEntry();
    zipOut.close();
    System.out.println("Done");

} catch ( Exception e ){
    // My catch block
}

My code so far creates a *.zipfile and insert the sample.txtfile.
My question is how would I be able to insert an existing file to the created *.zipfile?
If your answer has anything to do with TrueZIP, please post an SSCCE.

I have done the following:

到目前为止,我的代码创建了一个*.zip文件并插入了该sample.txt文件。
我的问题是如何将现有文件插入到创建的*.zip文件中?
如果您的回答与TrueZIP有任何关系,请发布 SSCCE。

我做了以下工作:

  • Googled
  • Search for existing question. ( Found few. No answer. Some didn't answer my particular question.
  • Read TrueZip. Yet, I couldn't understand a thing. ( Please do understand )
  • 谷歌搜索
  • 搜索现有问题。(发现很少。没有答案。有些没有回答我的特定问题。
  • 阅读TrueZip。然而,我什么也听不懂。(请理解)

回答by MadProgrammer

Using the inbuilt Java API. This will add a file to a Zip File, this will replace any existing Zip files that may exist, creating a new Zip file.

使用内置的 Java API。这会将文件添加到 Zip 文件,这将替换可能存在的任何现有 Zip 文件,创建一个新的 Zip 文件。

public class TestZip02 {

  public static void main(String[] args) {
    try {
      zip(new File("TextFiles.zip"), new File("sample.txt"));
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }

  public static void zip(File zip, File file) throws IOException {
    ZipOutputStream zos = null;
    try {
      String name = file.getName();
      zos = new ZipOutputStream(new FileOutputStream(zip));

      ZipEntry entry = new ZipEntry(name);
      zos.putNextEntry(entry);

      FileInputStream fis = null;
      try {
        fis = new FileInputStream(file);
        byte[] byteBuffer = new byte[1024];
        int bytesRead = -1;
        while ((bytesRead = fis.read(byteBuffer)) != -1) {
          zos.write(byteBuffer, 0, bytesRead);
        }
        zos.flush();
      } finally {
        try {
          fis.close();
        } catch (Exception e) {
        }
      }
      zos.closeEntry();

      zos.flush();
    } finally {
      try {
        zos.close();
      } catch (Exception e) {
      }
    }
  }
}

回答by Kanagaraj M

回答by ameed

It seems that, according to the epic JDK reference, you could use a while zis.getNextEntry() != nullloop to loop through the file (where zis is a ZipInputStream), then use zis.read()to read into an array, which is sent to an ArrayList or similar.

看来,根据史诗 JDK 参考,您可以使用while zis.getNextEntry() != null循环来循环遍历文件(其中 zis 是 ZipInputStream),然后用于zis.read()读入一个数组,该数组被发送到一个 ArrayList 或类似的。

Then, one could use toArray(), "cast" it to a bytearray with this methodand zos.write()it into the output ZIP file (where zos is a ZipOutputStream), using zos.putNextEntry()to make new entries. (You will need to save the ZipEntry and get its name with ze.getName(), with zebeing a ZipEntry.)You should replace Twith Byteand byte(use byteeverywhere but the forloop body) and may need to modify the casting code to use Byte.byteValue()to convert from Byte(wrapper class) to byte(primitive type), like so:

然后,可以使用toArray(),使用此方法将其“转换”为byte数组,并将zos.write()其放入输出 ZIP 文件(其中 zos 是 a ZipOutputStream)中,zos.putNextEntry()用于创建新条目。(您将需要保存 ZipEntry 并使用 获得它的名称ze.getName(),并且ze是一个ZipEntry。)您应该替换TBytebytebyte除了for循环体之外的任何地方都使用)并且可能需要修改转换代码以用于Byte.byteValue()Byte(包装类)转换为byte(原始类型),像这样:

for(int i = 0; i < objects.length; i++) {
    convertedObjects[i] = (Byte)objects[i].byteValue();
}

Note that this is untested and based on the JDK (entries ZipInputStream, ZipOutputStream, ArrayList, and Byte) and a Google search on array casting.

请注意,这是未经测试和基于JDK(条目ZipInputStreamZipOutputStreamArrayList,和Byte)和谷歌搜索上排列铸造。

Sorry if that was a bit dense, and hope this helps!!

对不起,如果这有点密集,希望这会有所帮助!!