如何在Java中创建ZIP文件?

8
这个jar命令在Java中有哪个等价命令?
C:\>jar cvf myjar.jar directory

我希望能够以编程方式创建此jar文件,因为我不能保证系统路径中有jar命令,我无法运行外部进程。
编辑:我只想将一个目录归档(并压缩)。不必遵循任何Java标准。例如:标准zip格式就可以。
2个回答

12
// 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) {
    }

您还可以使用此帖子的答案How to use JarOutputStream to create a JAR file?


你知道有一个名为JarOutputStream的类,它是ZipOutputStream的子类吗? - Powerlord
谢谢。看到了,但是我想要归档一个包含许多目录和文件的目录。我不想创建所有文件的输入数组。只想将目录作为输入传递。 - Marcus Leon
@Marcus,你需要编写递归迭代目录的代码。 - Romain Hippeau
不错,看起来你比我先完成了! - Brian T Hannan
正如你建议的那样,我最终采用了https://dev59.com/znM_5IYBdhLWcg3wq1CF中的答案。谢谢! - Marcus Leon

4

我修改了你的链接,因为导航栏左侧的框架是无用的。 - Powerlord
谢谢。有没有一个可以归档整个目录树的示例代码? - Marcus Leon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接