如何在 Java 中创建 ZIP 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2977663/
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-29 23:47:34  来源:igfitidea点击:

How do I create a ZIP file in Java?

javazip

提问by Marcus Leon

What is the Java equivalent to this jar command:

与此 jar 命令等效的 Java 是什么:

C:\>jar cvf myjar.jar directory

I'd like to create this jar file programmatically as I can't be assured that the jarcommand will be on the system path where I could just run the external process.

我想以编程方式创建这个 jar 文件,因为我不能保证jar命令将在我可以运行外部进程的系统路径上。

Edit: All I want is to archive (and compress) a directory. Doesn't have to follow any java standard. Ie: a standard zip is fine.

编辑:我想要的只是存档(并压缩)一个目录。不必遵循任何 Java 标准。即:标准拉链很好。

回答by Romain Hippeau

// These are the files to include in the ZIP file
    String[] source = new String[]{"source1", "source2"};

    // Create a buffer for reading the files
    byte[] buf = new byte[1024];

    try {
        // Create the ZIP file
        String target = "target.zip";
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(target));

        // Compress the files
        for (int i=0; i<source.length; i++) {
            FileInputStream in = new FileInputStream(source[i]);

            // Add ZIP entry to output stream.
            out.putNextEntry(new ZipEntry(source[i]));

            // 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();
    } catch (IOException e) {
    }

You can also use the answer from this post How to use JarOutputStream to create a JAR file?

您还可以使用这篇文章中的答案如何使用 JarOutputStream 创建 JAR 文件?

回答by whaley

Everything you'll want is in the java.util.jar package:

你想要的一切都在 java.util.jar 包中:

http://java.sun.com/javase/6/docs/api/java/util/jar/package-summary.html

http://java.sun.com/javase/6/docs/api/java/util/jar/package-summary.html