Creating a tar.gz with commons-compress
By jcscoobyrs on Mon, 08/16/2010 - 14:36Recently I needed to take a Linux-only Java application and make it work on Windows. One of the things I had to do was remove a lot of calls to command line utilities. One of those was where we used tar to create a tar.gz of a directory structure. Googling around for creating a tar.gz in Java quickly pointed me to the commons-compress project. The problem was that there was very little documentation and no full examples to go off of. I ended up getting this code working and below is an example. In this example you will see two Java methods that are heavily documented and use together will allow you to create a .tar.gz of a directory. Of course, this example could be made better and is simple for brevity. Enjoy.
/** * Creates a tar.gz file at the specified path with the contents of the specified directory. * * @param dirPath The path to the directory to create an archive of * @param archivePath The path to the archive to create * * @throws IOException If anything goes wrong */ public static void createTarGzOfDirectory(String directoryPath, String tarGzPath) throws IOException { GzipCompressorOutputStream gzOut = null; TarArchiveOutputStream tOut = null; try { gzOut = new GzipCompressorOutputStream(bOut); tOut = new TarArchiveOutputStream(gzOut); addFileToTarGz(tOut, directoryPath, ""); } finally { tOut.finish(); tOut.close(); gzOut.close(); bOut.close(); fOut.close(); } } /** * Creates a tar entry for the path specified with a name built from the base passed in and the file/directory * name. If the path is a directory, a recursive call is made such that the full directory is added to the tar. * * @param tOut The tar file's output stream * @param path The filesystem path of the file/directory being added * @param base The base prefix to for the name of the tar file entry * * @throws IOException If anything goes wrong */ private static void addFileToTarGz(TarArchiveOutputStream tOut, String path, String base) throws IOException { TarArchiveEntry tarEntry = new TarArchiveEntry(f, entryName); tOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); tOut.putArchiveEntry(tarEntry); if (f.isFile()) { tOut.closeArchiveEntry(); } else { tOut.closeArchiveEntry(); if (children != null) { addFileToTarGz(tOut, child.getAbsolutePath(), entryName + "/"); } } } }
The example could easily be tested by creating a static main method that looks like this:
... /** * Application entry point. * * @param args The command line arguments. */ { createTarGzOfDirectory("/Users/jwhitlock/some_directory", "/tmp/some_directory.tar.gz"); } ...
And there you have it...a complete example of how to use commons-compress to create a .tar.gz of a directory.













