Java - 压缩现有文件

Mic*_*dan 4 java zip append truezip

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

你好Java开发人员,

这是场景:

假设我有一个名为的文本文件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
}
Run Code Online (Sandbox Code Playgroud)

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

我做了以下事情:

  • 谷歌搜索
  • 搜索现有问题.(发现很少.没有答案.有些人没有回答我的具体问题.
  • 阅读TrueZip.然而,我无法理解一件事.(请理解)

Mad*_*mer 8

使用内置的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) {
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)