Java: JarOutputStream Example
Saturday, 01 May 2010 06:58

Below is an example of how to create a jar file from within a Java program using 'java.util.jar.JarOutputStream'.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;

public class MyMain {
	public static void main(String[] args) {
		try {
			/*Create a JarEntry from a file to add to a new jar file*/
			File testfile = new File("src/testfile.txt");
			if (testfile.exists() == false) {
				System.err.println("Error: File "+testfile.getAbsolutePath()+" not found.!");
				return;
			}
			JarEntry entry = new JarEntry(testfile.getAbsolutePath());
			
			/*Create the jar file*/
			File file = new File("src/myjar.jar");
			if (file.exists() == true) {
				/*Delete the jar file if it already exists*/
				file.delete();
			}
			FileOutputStream myfileout = new FileOutputStream(file);
			JarOutputStream jarout = new JarOutputStream(myfileout);
			
			
			/*Write test file to the jar file 
			 * - putNextEntry starts the new entry
			 * - read bytes from test file
			 * - write bytes to the jar file 
			 */
			jarout.putNextEntry(entry);
			FileInputStream filereader = new FileInputStream(testfile);
			final int buffersize = 1024; 
			byte buffer[] = new byte[buffersize]; 
			int readcount = 0; 
			while ((readcount = filereader.read(buffer, 0, buffersize)) >= 0) { 
				if (readcount > 0) { 
					jarout.write(buffer, 0, readcount); 
				} 
			} 
			
			jarout.close();
			System.out.println("Created jar file: "+file.getAbsoluteFile());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}