tags:

views:

91

answers:

3

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 I can't be assured that the jar command will be on the system path where I could just run the external process.

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.

+4  A: 

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

whaley
I edited your link because the left frame in the navigation is the useless one.
R. Bemrose
Thanks. Any sample code that archives an entire directory tree?
Marcus
+2  A: 
// 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 http://stackoverflow.com/questions/1281229/how-to-use-jaroutputstream-to-create-a-jar-file

Romain Hippeau
er... you know that there are is a `JarOutputStream` that is a child class of `ZipOutputStream`?
R. Bemrose
Thanks.. Saw that, but looking to just archive a directory that contains many directories and files. I don't want to have to create an input array of all the files. Just want to pass the directory as input.
Marcus
@Marcus you are going to need to code for recursively iterating through the directories.
Romain Hippeau
@R. Bemrose - updated my post to reflect your suggestion
Romain Hippeau
Nice, looks like you beat me to it!
Brian T Hannan
As you suggested, I did in the end take the answer from http://stackoverflow.com/questions/1281229/how-to-use-jaroutputstream-to-create-a-jar-file. Thanks!
Marcus
A: 

JarOutputStream would be my guess. http://www.daniweb.com/forums/thread16028.html

Brian T Hannan