Java code to create a JAR file

What is the Java equivalent of this jar command:

C:\>jar cvf myjar.jar directory 

I would like to create this jar file programmatically, since I cannot be sure that the jar command will be on the system path, where I could just start the external process.

Edit: all I want is to archive (and compress) the directory. No java standard needs to be followed. Those. The standard zipper is ok.

+7
java jar
source share
3 answers
 // 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 response from this post How to use a JarOutputStream to create a JAR file?

+11
source share
+4
source share

JarOutputStream will be my hunch. http://www.daniweb.com/forums/thread16028.html

+1
source share

All Articles