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;
2  
3  import java.io.File;
4  import java.io.FileOutputStream;
5  import java.io.IOException;
6  import java.util.jar.JarFile;
7  import java.util.jar.Pack200;
8  import java.util.jar.Pack200.Packer;
9  
10 public class Demo1 {
11  public static void main(String[] args) {
12      Packer packer = Pack200.newPacker();
13      File packFile = new File("test.pack");
14      
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 }

Explanation

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s