Thursday, July 2, 2015

Manipulating Java Archives

Java bundles deployable files in formats like jar, war and ear. These files are basically zipped files which is understood by Java environment or Java EE compliant servers. Various tools available to be used with zip files can be used with these Java archived files as well. This post, I will be covering how to manipulate these file through command prompt. We can use jar utility to manipulate Java archives files. 

Java Archived Formats = jar, war, ear 

In the below examples, I have used only one file format (mostly jar) but you can certainly run the command on with other formats (war and ear) as well. 

Listing Content

jar command can be used to list the content of Java archives. Below command shows the list of all files on the console.

$jar tvf <<file.jar | file.war | file.ear>>
$jar tvf gson-2.2.1.jar

t - > list content of archive
v -> in verbose mode
f -> file name specified

The response of the above command can be pretty huge, so if you looking for any specific file use grep to filter that specific file. 

$jar tvf gson-2.2.1.jar | grep Gson.class
18281 Fri May 11 11:48:48 IST 2012 com/google/gson/Gson.class

Extracting Content

The contents of the archived file can be extracted with the x (i.e. extract) option. 

$jar xvf gson-2.2.1.jar

Above command will extract all files from the jar. In some cases you might just be interested in a particular file from the jar (or war or ear). This can be achieved by giving file name as shown below:

$jar xvf gson-2.2.1.jar com/google/gson/Gson.class
-rw-r--r--  1 Siddheshwar  staff  189617 Jul  2 16:54 gson-2.2.1.jar
drwxr-xr-x  3 Siddheshwar  staff     102 Jul  2 16:55 com

So above command creates a directory with name com. If you follow the proper path com/google/gson you will see just single file. One alternative to above approach is that unarchive the whole jar file but grep for the specific file which you are looking for. If it's present, the console will show it as output in the next line (as shown below).

$jar xvf gson-2.2.1.jar | grep Gson.class
inflated: com/google/gson/Gson.class


No comments:

Post a Comment