How do I compress or zip a directory recursively?

In this example you are going to learn how to zip or compress a directory recursively. The zip file format allows us to compress multiple files. We use the to compress the file. Each entry in the zip file is represented by the class.

To compress a directory we must first get all the list of files in the specified directory and including all files in the sub directory. In the example this task is handled by the getFileList() method. This method store the file list in the fileList variable to be use later during the compression process to create the ZipEntry.

Below is the code example showing you how to compress multiple files using zip.

The code snippet above will compress the D:Data directory and it will produce a zip file called When running the program you can see something like this in the console:


How do I decompress a GZip file in Java?

In the previous example we have learn how to compress a file in GZIP format. To get the file back to its original version we will now learn how to decompress the GZip file. Equals to the preview example, we are also going to use the FileInputStream and FileOutputStream class to read the compressed source file and to write out the decompressed file. While GZipOutputStream was used to to create the GZIp file, the GZipInputStream is the class that handles the decompression.

Here is your code snippet:


How do I compress a file in GZip format?

In this code example you’ll learn how to compress a file using the GZip compression. By its nature, GZip can only compress a single file, you can not use it for compressing a directory and all the files in that directory. Classes that you will be using to compress a file in GZip format includes the GZipOutputStream, FileInputStream and FileOutputStream classes. The steps for compressing a file described in the comments of the code snippet below.