How to Zip a Folder in Java

In the post How to Zip Files in Java we have seen how to zip a single file or multiple files in Java but you may also need to zip a folder in Java where you also retain the folder tree structure while zipping it. This post shows how to zip a folder in Java where the zip archive contains the whole tree structure (files and subdirectories).

Options for zipping a folder in Java

For zipping a folder with all its subfolders and files two options are given in this post.

  1. Using Files.walkFileTree method– Using this method you can recursively visit all the files in a file tree. An implementation of FileVisitor interface is provided to the Files.walkFileTree method to visit each file in a file tree. This option is available Java 7 onward.
  2. By providing the code yourself to read the files with in a folder recursively.

Check this post How to Unzip a File in Java to see how to unzip files and folders in Java.

Directory structure used

Java programs shown here to zip a folder in Java use the following directory structure.

zip a folder in Java

With in the parent folder there is one sub folder Child with two files and one file is stored in the parent folder. The zipped archive should retain the same tree structure.

Using Files.walkFileTree method to zip a folder in Java

One of the argument of this method is a FileVisitor interface. You do need to provide implementation of this interface as per your requirement.

FileVisitor interface has four methods, for zipping a folder you do need to implement two of them.

  • preVisitDirectory – Invoked before a directory’s entries are visited. By implementing this method you can create the visited folder with in the zip archive.
  • visitFile – Invoked on the file being visited. By implementing this method you can add each visited file to the zip archive.

Output

Zip a folder in Java by listing files recursively

In the code you first create a list of all the files and folders residing with in a parent folder.
Once you have this folder tree structure in a list you iterate through that list to create a zip archive. For every iterated element of the list you check if it is a directory or a file-
If it is a directory then you just add the name of the directory in the zip archive.
If it is a file then you add the name as well as the content of the file.

That’s all for the topic How to Zip a Folder in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.