【问题标题】:How do I create a ZIP file in Java?如何在 Java 中创建 ZIP 文件?
【发布时间】:2011-02-27 23:48:09
【问题描述】:

这个jar命令对应的Java是什么:

C:\>jar cvf myjar.jar directory

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

编辑:我想要的只是归档(和压缩)一个目录。不必遵循任何 java 标准。即:一个标准的拉链就可以了。

【问题讨论】:

    标签: java zip


    【解决方案1】:
    // 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?

    【讨论】:

    • er...你知道有一个JarOutputStreamZipOutputStream 的子类吗?
    • 谢谢.. 看到了,但只想归档一个包含许多目录和文件的目录。我不想创建所有文件的输入数组。只想将目录作为输入传递。
    • @Marcus 您将需要编写递归迭代目录的代码。
    • 不错,看来你比我快了!
    • 按照你的建议,我最终还是从stackoverflow.com/questions/1281229/…那里得到了答案。谢谢!
    【解决方案2】:

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

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

    【讨论】:

    • 我编辑了您的链接,因为导航中的左侧框架是无用的。
    • 谢谢。存档整个目录树的任何示例代码?
    猜你喜欢
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    • 2023-03-12
    • 1970-01-01
    • 2013-09-06
    • 2015-08-31
    相关资源
    最近更新 更多