Unzip a .jar file in Java program

Here is a method that can unzip/unjar .jar file and extract files inside to a destination directory.

There are mainly 2 steps:
1) Create all directories inside of the jar file
2) Create all files inside of the jar file

Since files in .jar is not in a certain order, we need to iterate twice to achieve the 2 steps.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.Enumeration;
 
public class UnzipJar {
 
	public static void main(String[] args) throws IOException {
		unzipJar("./src/dest", "./src/a.jar");
	}
 
	public static void unzipJar(String destinationDir, String jarPath) throws IOException {
		File file = new File(jarPath);
		JarFile jar = new JarFile(file);
 
		// fist get all directories,
		// then make those directory on the destination Path
		for (Enumeration<JarEntry> enums = jar.entries(); enums.hasMoreElements();) {
			JarEntry entry = (JarEntry) enums.nextElement();
 
			String fileName = destinationDir + File.separator + entry.getName();
			File f = new File(fileName);
 
			if (fileName.endsWith("/")) {
				f.mkdirs();
			}
 
		}
 
		//now create all files
		for (Enumeration<JarEntry> enums = jar.entries(); enums.hasMoreElements();) {
			JarEntry entry = (JarEntry) enums.nextElement();
 
			String fileName = destinationDir + File.separator + entry.getName();
			File f = new File(fileName);
 
			if (!fileName.endsWith("/")) {
				InputStream is = jar.getInputStream(entry);
				FileOutputStream fos = new FileOutputStream(f);
 
				// write contents of 'is' to 'fos'
				while (is.available() > 0) {
					fos.write(is.read());
				}
 
				fos.close();
				is.close();
			}
		}
	}
}

To unzip a .zip file, the approach is exactly the same, just replace the class "JarFile" with "java.util.zip.ZipFile".

Category >> Real Methods  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Brian Krahmer

    Thanks for the code, but don’t read and write one byte at a time if you care about performance!