63

我目前正在提取一个war文件的内容,然后将一些新文件添加到目录结构中,然后创建一个新的war文件。

这一切都是从Java以编程方式完成的 - 但我想知道复制战争文件然后只是附加文件是否会更有效 - 那么只要战争扩大然后我就不必等待再次被压缩。

我似乎无法在文档或任何在线示例中找到执行此操作的方法。

任何人都可以提供一些提示或指示吗?

更新:

其中一个答案中提到的 TrueZip 似乎是一个非常好的 Java 库,可以附加到 zip 文件中(尽管其他答案说不可能这样做)。

任何人都有关于 TrueZip 的经验或反馈,或者可以推荐其他类似的库吗?

4

13 回答 13

95

在 Java 7 中,我们得到了Zip 文件系统,它允许在 zip(jar、war)中添加和更改文件,而无需手动重新打包。

我们可以直接写入 zip 文件中的文件,如下例所示。

Map<String, String> env = new HashMap<>(); 
env.put("create", "true");
Path path = Paths.get("test.zip");
URI uri = URI.create("jar:" + path.toUri());
try (FileSystem fs = FileSystems.newFileSystem(uri, env))
{
    Path nf = fs.getPath("new.txt");
    try (Writer writer = Files.newBufferedWriter(nf, StandardCharsets.UTF_8, StandardOpenOption.CREATE)) {
        writer.write("hello");
    }
}
于 2013-07-06T15:05:04.833 回答
50

正如其他人提到的,不可能将内容附加到现有的 zip(或战争)。但是,可以即时创建新的 zip,而无需临时将提取的内容写入磁盘。很难猜测这会快多少,但它是使用标准 Java 可以获得的最快速度(至少据我所知)。正如 Carlos Tasada 所提到的,SevenZipJBindings 可能会为您节省一些额外的时间,但是将这种方法移植到 SevenZipJBindings 仍然会比使用具有相同库的临时文件更快。

下面是一些写入现有 zip (war.zip) 内容并将额外文件 (answer.txt) 附加到新 zip (append.zip) 的代码。只需要 Java 5 或更高版本,不需要额外的库。

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class Main {

    // 4MB buffer
    private static final byte[] BUFFER = new byte[4096 * 1024];

    /**
     * copy input to output stream - available in several StreamUtils or Streams classes 
     */    
    public static void copy(InputStream input, OutputStream output) throws IOException {
        int bytesRead;
        while ((bytesRead = input.read(BUFFER))!= -1) {
            output.write(BUFFER, 0, bytesRead);
        }
    }

    public static void main(String[] args) throws Exception {
        // read war.zip and write to append.zip
        ZipFile war = new ZipFile("war.zip");
        ZipOutputStream append = new ZipOutputStream(new FileOutputStream("append.zip"));

        // first, copy contents from existing war
        Enumeration<? extends ZipEntry> entries = war.entries();
        while (entries.hasMoreElements()) {
            ZipEntry e = entries.nextElement();
            System.out.println("copy: " + e.getName());
            append.putNextEntry(e);
            if (!e.isDirectory()) {
                copy(war.getInputStream(e), append);
            }
            append.closeEntry();
        }

        // now append some extra content
        ZipEntry e = new ZipEntry("answer.txt");
        System.out.println("append: " + e.getName());
        append.putNextEntry(e);
        append.write("42\n".getBytes());
        append.closeEntry();

        // close
        war.close();
        append.close();
    }
}
于 2010-02-15T10:17:41.530 回答
27

我曾经有过类似的要求 - 但它是用于读取和写入 zip 档案(.war 格式应该类似)。我尝试使用现有的 Java Zip 流来完成它,但发现编写部分很麻烦——尤其是在涉及目录时。

我建议您尝试使用TrueZIP(开源 - apache 风格许可)库,它将任何存档公开为虚拟文件系统,您可以像普通文件系统一样在其中读取和写入。它对我来说就像一种魅力,极大地简化了我的开发。

于 2010-02-12T12:13:45.177 回答
14

你可以使用我写的这段代码

public static void addFilesToZip(File source, File[] files)
{
    try
    {

        File tmpZip = File.createTempFile(source.getName(), null);
        tmpZip.delete();
        if(!source.renameTo(tmpZip))
        {
            throw new Exception("Could not make temp file (" + source.getName() + ")");
        }
        byte[] buffer = new byte[1024];
        ZipInputStream zin = new ZipInputStream(new FileInputStream(tmpZip));
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(source));

        for(int i = 0; i < files.length; i++)
        {
            InputStream in = new FileInputStream(files[i]);
            out.putNextEntry(new ZipEntry(files[i].getName()));
            for(int read = in.read(buffer); read > -1; read = in.read(buffer))
            {
                out.write(buffer, 0, read);
            }
            out.closeEntry();
            in.close();
        }

        for(ZipEntry ze = zin.getNextEntry(); ze != null; ze = zin.getNextEntry())
        {
            out.putNextEntry(ze);
            for(int read = zin.read(buffer); read > -1; read = zin.read(buffer))
            {
                out.write(buffer, 0, read);
            }
            out.closeEntry();
        }

        out.close();
        tmpZip.delete();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
于 2012-01-12T02:04:11.680 回答
3

我不知道有你描述的Java库。但是你描述的很实用。您可以在 .NET 中使用DotNetZip进行操作。

Michael Krauklis 是正确的,您不能简单地将数据“附加”到战争文件或 zip 文件中,但这并不是因为严格来说,在战争文件中存在“文件结束”指示。这是因为 war (zip) 格式包含一个目录,该目录通常位于文件末尾,其中包含 war 文件中各种条目的元数据。天真地附加到一个war文件会导致目录没有更新,所以你只有一个附加了垃圾的war文件。

需要的是一个理解格式的智能类,并且可以读取+更新war文件或zip文件,包括适当的目录。DotNetZip 执行此操作,无需解压缩/重新压缩未更改的条目,就像您描述或希望的那样。

于 2010-02-10T16:06:01.050 回答
2

正如 Cheeso 所说,没有办法做到这一点。AFAIK zip 前端的功能与您在内部的功能完全相同。

无论如何,如果您担心提取/压缩所有内容的速度,您可能想尝试SevenZipJBindings库。

几个月前,我在我的博客中介绍了这个库(对于自动推广感到抱歉)。举个例子,使用 java.util.zip 提取一个 104MB 的 zip 文件需要 12 秒,而使用这个库需要 4 秒。

在这两个链接中,您都可以找到有关如何使用它的示例。

希望能帮助到你。

于 2010-02-12T11:41:10.143 回答
1

请参阅此错误报告

对任何类型的结构化数据(如 zip 文件或 tar 文件)使用附加模式并不是您真正期望的工作。这些文件格式具有内置于数据格式中的内在“文件结束”指示。

如果你真的想跳过 un-waring/re-waring 的中间步骤,你可以读取 war 文件,获取所有 zip 条目,然后写入一个新的 war 文件“附加”你想要添加的新条目。不完美,但至少是一个更自动化的解决方案。

于 2010-02-08T17:19:20.280 回答
1

另一个解决方案:您可能会发现下面的代码在其他情况下也很有用。我已经用 ant 这种方式编译 Java 目录,生成 jar 文件,更新 zip 文件,...

    public static void antUpdateZip(String zipFilePath, String libsToAddDir) {
    Project p = new Project();
    p.init();

    Target target = new Target();
    target.setName("zip");
    Zip task = new Zip();
    task.init();
    task.setDestFile(new File(zipFilePath));
    ZipFileSet zipFileSet = new ZipFileSet();
    zipFileSet.setPrefix("WEB-INF/lib");
    zipFileSet.setDir(new File(libsToAddDir));
    task.addFileset(zipFileSet);
    task.setUpdate(true);

    task.setProject(p);
    task.init();
    target.addTask(task);
    target.setProject(p);
    p.addTarget(target);

    DefaultLogger consoleLogger = new DefaultLogger();
    consoleLogger.setErrorPrintStream(System.err);
    consoleLogger.setOutputPrintStream(System.out);
    consoleLogger.setMessageOutputLevel(Project.MSG_DEBUG);
    p.addBuildListener(consoleLogger);

    try {
        // p.fireBuildStarted();

        // ProjectHelper helper = ProjectHelper.getProjectHelper();
        // p.addReference("ant.projectHelper", helper);
        // helper.parse(p, buildFile);
        p.executeTarget(target.getName());
        // p.fireBuildFinished(null);
    } catch (BuildException e) {
        p.fireBuildFinished(e);
        throw new AssertionError(e);
    }
}
于 2011-03-28T19:33:51.350 回答
1

这是一个使用 servlet 获得响应并发送响应的简单代码

myZipPath = bla bla...
    byte[] buf = new byte[8192];
    String zipName = "myZip.zip";
    String zipPath = myzippath+ File.separator+"pdf" + File.separator+ zipName;
    File pdfFile = new File("myPdf.pdf");
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath));
    ZipEntry zipEntry = new ZipEntry(pdfFile.getName());
    out.putNextEntry(zipEntry);
    InputStream in = new FileInputStream(pdfFile);
    int len;
    while ((len = in.read(buf)) > 0) {
         out.write(buf, 0, len);
     }
    out.closeEntry();
    in.close();
     out.close();
                FileInputStream fis = new FileInputStream(zipPath);
                response.setContentType("application/zip");
                response.addHeader("content-disposition", "attachment;filename=" + zipName);
    OutputStream os = response.getOutputStream();
            int length = is.read(buffer);
            while (length != -1)
            {
                os.write(buffer, 0, length);
                length = is.read(buffer);
            }
于 2014-09-11T13:12:20.097 回答
1

以下是如何使用TrueVFS轻松地将文件附加到现有 zip 的示例:

// append a file to archive under different name
TFile.cp(new File("existingFile.txt"), new TFile("archive.zip", "entry.txt"));

// recusively append a dir to the root of archive
TFile src = new TFile("dirPath", "dirName");
src.cp_r(new TFile("archive.zip", src.getName()));

TrueVFS 是 TrueZIP 的继承者,在适当的时候使用 Java 7 NIO 2 特性,但提供了更多特性,如线程安全异步并行压缩。

还要注意 Java 7 ZipFileSystem 默认情况下在大量输入时容易受到 OutOfMemoryError的影响。

于 2016-09-12T19:16:54.877 回答
0

这是 Liam 答案的 Java 1.7 版本,它使用资源和 Apache Commons IO 进行尝试。

输出被写入一个新的 zip 文件,但可以很容易地修改它以写入原始文件。

  /**
   * Modifies, adds or deletes file(s) from a existing zip file.
   *
   * @param zipFile the original zip file
   * @param newZipFile the destination zip file
   * @param filesToAddOrOverwrite the names of the files to add or modify from the original file
   * @param filesToAddOrOverwriteInputStreams the input streams containing the content of the files
   * to add or modify from the original file
   * @param filesToDelete the names of the files to delete from the original file
   * @throws IOException if the new file could not be written
   */
  public static void modifyZipFile(File zipFile,
      File newZipFile,
      String[] filesToAddOrOverwrite,
      InputStream[] filesToAddOrOverwriteInputStreams,
      String[] filesToDelete) throws IOException {


    try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(newZipFile))) {

      // add existing ZIP entry to output stream
      try (ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile))) {
        ZipEntry entry = null;
        while ((entry = zin.getNextEntry()) != null) {
          String name = entry.getName();

          // check if the file should be deleted
          if (filesToDelete != null) {
            boolean ignoreFile = false;
            for (String fileToDelete : filesToDelete) {
              if (name.equalsIgnoreCase(fileToDelete)) {
                ignoreFile = true;
                break;
              }
            }
            if (ignoreFile) {
              continue;
            }
          }

          // check if the file should be kept as it is
          boolean keepFileUnchanged = true;
          if (filesToAddOrOverwrite != null) {
            for (String fileToAddOrOverwrite : filesToAddOrOverwrite) {
              if (name.equalsIgnoreCase(fileToAddOrOverwrite)) {
                keepFileUnchanged = false;
              }
            }
          }

          if (keepFileUnchanged) {
            // copy the file as it is
            out.putNextEntry(new ZipEntry(name));
            IOUtils.copy(zin, out);
          }
        }
      }

      // add the modified or added files to the zip file
      if (filesToAddOrOverwrite != null) {
        for (int i = 0; i < filesToAddOrOverwrite.length; i++) {
          String fileToAddOrOverwrite = filesToAddOrOverwrite[i];
          try (InputStream in = filesToAddOrOverwriteInputStreams[i]) {
            out.putNextEntry(new ZipEntry(fileToAddOrOverwrite));
            IOUtils.copy(in, out);
            out.closeEntry();
          }
        }
      }

    }

  }
于 2014-01-27T15:10:29.260 回答
0

这 100% 有效,如果您不想使用额外的库 .. 1) 首先,将文件附加到 zip 的类 ..

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class AddZip {

    public void AddZip() {
    }

    public void addToZipFile(ZipOutputStream zos, String nombreFileAnadir, String nombreDentroZip) {
        FileInputStream fis = null;
        try {
            if (!new File(nombreFileAnadir).exists()) {//NO EXISTE 
                System.out.println(" No existe el archivo :  " + nombreFileAnadir);return;
            }
            File file = new File(nombreFileAnadir);
            System.out.println(" Generando el archivo '" + nombreFileAnadir + "' al ZIP ");
            fis = new FileInputStream(file);
            ZipEntry zipEntry = new ZipEntry(nombreDentroZip);
            zos.putNextEntry(zipEntry);
            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {zos.write(bytes, 0, length);}
            zos.closeEntry();
            fis.close();

        } catch (FileNotFoundException ex ) {
            Logger.getLogger(AddZip.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(AddZip.class.getName()).log(Level.SEVERE, null, ex);
        } 
    }

}

2)你可以在你的控制器中调用它..

//in the top
try {
fos = new FileOutputStream(rutaZip);
zos =   new ZipOutputStream(fos);
} catch (FileNotFoundException ex) {
Logger.getLogger(UtilZip.class.getName()).log(Level.SEVERE, null, ex);
}

...
//inside your method
addZip.addToZipFile(zos, pathFolderFileSystemHD() + itemFoto.getNombre(), "foto/" + itemFoto.getNombre());
于 2016-02-16T20:00:56.273 回答
0

根据上面@sfussenegger 给出的答案,以下代码用于附加到 jar 文件并下载它:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    Resource resourceFile = resourceLoader.getResource("WEB-INF/lib/custom.jar");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (ZipOutputStream zos = new ZipOutputStream(baos, StandardCharsets.ISO_8859_1);) {
        try (ZipFile zin = new ZipFile(resourceFile.getFile(), StandardCharsets.ISO_8859_1);) {
            zin.stream().forEach((entry) -> {
                try {
                    zos.putNextEntry(entry);
                    if (!entry.isDirectory()) {
                        zin.getInputStream(entry).transferTo(zos);
                    }
                    zos.closeEntry();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            });
        }
        /* build file records to be appended */
        ....
        for (FileContents record : records) {
            zos.putNextEntry(new ZipEntry(record.getFileName()));
            zos.write(record.getBytes());
            zos.closeEntry();
        }
        zos.flush();
    }

    response.setContentType("application/java-archive");
    response.setContentLength(baos.size());
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"custom.jar\"");
    try (BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream())) {
        baos.writeTo(out);
    }
}
于 2020-03-29T14:51:22.677 回答