简体   繁体   English

如何用Java创建ZIP文件?

[英]How do I create a ZIP file in Java?

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 jar command 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. 不必遵循任何java标准。 Ie: a standard zip is fine. 即:标准拉链很好。

// 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文件?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM