Compressing JAR file

JAR file is file archiver which collects/groups different files and folder into a format which represents one file.

The format of JAR file is an uncompressed format.

Pack200 is a tool that can be used to compress jar file.

Below is a simple example of how we can use Pack200 tool to compress the file

Main Code

1  package Pack200.Packer;
3  import;
4  import;
5  import;
6  import java.util.jar.JarFile;
7  import java.util.jar.Pack200;
8  import java.util.jar.Pack200.Packer;
10 public class Demo1 {
11  public static void main(String[] args) {
12      Packer packer = Pack200.newPacker();
13      File packFile = new File("test.pack");
15      try (JarFile jarFile = new JarFile("jsonb-ri-1.0.jar");
16          FileOutputStream fos = new FileOutputStream(packFile)) {
17          packer.pack(jarFile, fos);
18      } catch(IOException excep) {
19          excep.printStackTrace();
20      }
21  }
22 }


In the above code we compress the jsonb-ri-1.0.jar file to test.pack file.

At line 12 we create an instance of Packer, which compresses the file, as shown below
Packer packer = Pack200.newPacker();

At line 13 we create the destination file test.pack.

At line 15 we create an instance of JarFile which represents the jar file to be compressed.

At line 16 we create an instance of FileOutputStream, the stream through which data is moved to the destination file.

At line 17, we compress the jar file using pack method, which takes two arguments which are
1) The jar file which has to be compressed.
2) The output stream to which compressed data has to be sent.

Leave a Reply