How do I create a ZIP file in Java?

后端 未结 2 1519
孤街浪徒
孤街浪徒 2020-12-11 03:23

What is the Java equivalent to this jar command:

C:\\>jar cvf myjar.jar directory

I\'d like to create this jar file programmatically as

相关标签:
2条回答
  • 2020-12-11 04:08
    // 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?

    0 讨论(0)
  • 2020-12-11 04:10

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

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

    0 讨论(0)
提交回复
热议问题