UNIX: Archiving and Compression or For tar Use jar

We often have to send files from one machine to another. The age old technique for doing this is to create an archive using tar of the files and then to compress them with compress or gzip. However, there is another free technique available: jar.

Jar has the following advantages:

  • jar is free.
  • jar is truly multi platform (UNIX, Linux, all the various Windi, Mac plus others).
  • jar is scriptable - i.e. it has a command line interface.
  • tar scripts can be converted to jar by changing one letter (generally).
  • jar compresses as it goes (unless you tell it not to).

So how do you get hold of such a gem?

Jar comes as part of the Java Development Kit (JDK). It can be downloaded from www.javasoft.com.

So how do I use jar?

Although jar has many options, the most relevant are below:

Create a jar file (c:\temp\allfiles.jar) containing all the files in the current directory:

jar cvMf c:\temp\allfiles.jar *

Note: The "M" parameter ensures that a manifest directory and file is not added to the jar file.

Check what is in the jar file (c:\temp\allfiles.jar):

jar tvf c:\temp\allfiles.jar *

Extract all the files back out from the jar file into (potentially another) current directory:

jar xvf c:\temp\allfiles.jar

Extract just the file thisone.txt from the jar file into (potentially another) current directory:

jar xvf c:\temp\allfiles.jar thisone.txt

Note: if the file is a directory, then all the files below that directory get extracted too.

Key differences between tar and jar:

  • tar does not have an M flag. It does not create a manifest file
  • tar cvf file * would extract all files from a tar file, the equivalent jar does not need an "*".
  • tar does not by default keep empty directories. jar does.

Key differences between winzip and jar:

  • winzip errors if there are two files with the same name in the directories saved. jar does not.
  • In our tests, winzip creates just slightly larger archives than jar at normal compression, but creates smaller ones at maixmum compression

Summary

jar can make an easy to script compressing and archiving utility on Windows and Unix, particularly if passing information between the two operating systems.

Computing Articles