Unzipping a jar file programmatically

In this post, I will explain how to unzip a jar file.

Below is the complete code to unzipping a jar file programmatically

Main code


1  package jar;
2  
3  import java.io.File;
4  import java.io.FileOutputStream;
5  import java.io.IOException;
6  import java.io.InputStream;
7  import java.util.Enumeration;
8  import java.util.jar.JarEntry;
9  import java.util.jar.JarFile;
10 
11 public class JarDemo2 {
12  public static void main(String[] args) throws IOException {
13      String destination = "mockito-core-2.11.0";
14         try (JarFile jarFile = new JarFile("mockito-core-2.11.0.jar")){
15             File folder = new File(destination);
16             folder.mkdir();
17             for (Enumeration e = jarFile.entries(); e.hasMoreElements();) {
18              JarEntry jarEntry = e.nextElement();
19                 if(jarEntry.isDirectory()) {
20                     File childFolder = new File(folder, jarEntry.getName());
21                     childFolder.mkdir();
22                 } else {
23                     try(FileOutputStream fos = new FileOutputStream(folder.getAbsolutePath() + "\\" + jarEntry.getName())) {
24                         InputStream zis = jarFile.getInputStream(jarEntry);
25                         byte[] data = new byte[1024];
26 
27                         int bytesRead = zis.read(data);
28                         while(bytesRead != -1) {
29                             fos.write(data,0,bytesRead);
30                             bytesRead = zis.read(data);
31                         }
32                         fos.flush();
33                         fos.close();
34                     }
35                 }
36             }
37         }
38  }
39 }

An instance of JarFile represents the jar file to be unzip. Refer to line 14.

An instance of JarEntry represents each entry (which can be a folder or file) in the jar file which has to be extracted. Refer to line 18.

We can check whether an entry represents a directory or not using the isDirectory method in JarEntry class. Refer to line 19.

In the above code if block creates a directory in the destination folder and else block extracts the file.

At line 24, we get the inputstream for the specified jarEntry. Read the inputstream and write to outputstream until -1 is reached. This is repeated for all the jar entries.

In this way we will unzip the jar files.


Check these products on Amazon

Leave a Reply