2010-02-02 527 views
1

我使用java的java.util.zip api将文件和文件夹添加到zip文件,但是当我将多个文件添加到同一个文件夹时,它删除了旧内容。有什么办法可以将文件添加到压缩文件中,而无需修改文件夹中的现有内容? 请帮忙,它的重要!使用JAVA将文件夹添加到zip文件中

这是我的示例代码:

ZipOutputStream zip = null; 
FileOutputStream fileWriter = null; 
fileWriter = new FileOutputStream(destZipFile); 
zip = new ZipOutputStream(fileWriter); 
zip.putNextEntry(new ZipEntry(destFilePath)); 
zip.write(content); 
zip.flush(); 
zip.close(); 
+0

这是我的示例代码: ZipOutputStream zip = null; \t \t FileOutputStream fileWriter = null; \t \t fileWriter = new FileOutputStream(destZipFile); \t \t zip = new ZipOutputStream(fileWriter); \t \t zip.putNextEntry(new ZipEntry(destFilePath)); \t \t \t zip.write(content); \t \t zip.flush(); \t \t zip.close(); – stanley 2010-02-02 10:09:48

+0

自从'close()'调用'flush()'本身之后,在调用'close()'时不需要调用'flush()'。 – uckelman 2010-02-02 12:17:21

回答

2

如果你想一个新的文件添加到现有的zip文件,你必须先解压缩一切,然后添加的所有文件,并再次压缩。

查看this link的样本。

1

我找到了一次......它创建一个临时文件,并在添加额外文件之前将现有zip文件中的所有文件添加到“新”zip文件中。如果两个文件具有相同的名称,则只会添加“最新”的文件。

public static void addFilesToExistingZip(File zipFile, 
     File[] files) throws IOException { 
      // get a temp file 
    File tempFile = File.createTempFile(zipFile.getName(), null); 
      // delete it, otherwise you cannot rename your existing zip to it. 
    tempFile.delete(); 

    boolean renameOk=zipFile.renameTo(tempFile); 
    if (!renameOk) 
    { 
     throw new RuntimeException("could not rename the file "+zipFile.getAbsolutePath()+" to "+tempFile.getAbsolutePath()); 
    } 
    byte[] buf = new byte[1024]; 

    ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile)); 
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile)); 

    ZipEntry entry = zin.getNextEntry(); 
    while (entry != null) { 
     String name = entry.getName(); 
     boolean notInFiles = true; 
     for (File f : files) { 
      if (f.getName().equals(name)) { 
       notInFiles = false; 
       break; 
      } 
     } 
     if (notInFiles) { 
      // Add ZIP entry to output stream. 
      out.putNextEntry(new ZipEntry(name)); 
      // Transfer bytes from the ZIP file to the output file 
      int len; 
      while ((len = zin.read(buf)) > 0) { 
       out.write(buf, 0, len); 
      } 
     } 
     entry = zin.getNextEntry(); 
    } 
    // Close the streams   
    zin.close(); 
    // Compress the files 
    for (int i = 0; i < files.length; i++) { 
     InputStream in = new FileInputStream(files[i]); 
     // Add ZIP entry to output stream. 
     out.putNextEntry(new ZipEntry(files[i].getName())); 
     // Transfer bytes from the file to the ZIP file 
     int len; 
     while ((len = in.read(buf)) > 0) { 
      out.write(buf, 0, len); 
     } 
     // Complete the entry 
     out.closeEntry(); 
     in.close(); 
    } 
    // Complete the ZIP file 
    out.close(); 
    tempFile.delete(); 
} 

编辑: 我觉得这是超过2岁,所以可能有些事情是不是真的是最新的了。

相关问题