Java Zip File Folder Example

Today we will look into java zip file example. We will also compress a folder and create zip file using java program.

Java ZIP can be used to compress a file into ZIP format. Since a zip file can contain multiple entries, ZipOutputStream uses to represent a zip file entry.

Java ZIP File

Creating a zip archive for a single file is very easy, we need to create a ZipOutputStream object from the FileOutputStream object of destination file. Then we add a new ZipEntry to the ZipOutputStream and use FileInputStream to read the source file to ZipOutputStream object. Once we are done writing, we need to close ZipEntry and release all the resources.

Java Zip Folder

Zipping a directory is little tricky, first we need to get the files list as absolute path. Then process each one of them separately. We need to add a ZipEntry for each file and use FileInputStream to read the content of the source file to the ZipEntry corresponding to that file.

Java Zip Example

Here is the java program showing how to zip a single file or zip a folder in java.

Output of the above java zip example program is:

Notice that while logging files to zip in directory, I am printing absolute path. But while adding zip entry, I am using relative path from the directory so that when we unzip it, it will create the same directory structure. That’s all for Java zip example.

By admin

Leave a Reply

%d bloggers like this: