How to Zip Files in Java

This post shows how you can zip files in Java. Using the options given here you can zip a single file or more than one file by specifying all those files.

Zip a file in Java

To zip files in Java there are two options-

  1. Using ZipOutputStream and ZipEntry classes residing in java.util.zip package.
  2. Using the Zip File System Provider– The zip file system provider treats a zip or JAR file as a file system and provides the ability to manipulate the contents of the file. The zip file system provider was introduced in the JDK 7 release.

Want to zip a folder, check this post How to Zip a Folder in Java

Zipping single fie in Java using ZipOutputStream

The steps for zipping a file using ZipOutputStream are as follows-

  • Create an InputStream for reading the source file.
  • Create an OutputStream for the zip file and wrap it in a ZipOutputStream object.
  • Create a ZipEntry instance for the source file and add it to the ZipOutputStream.
  • Read data from the source file and write it to the ZIP file.
  • Close the streams.

Zipping single fie in Java using Zip File System Provider

You can use the factory methods of the java.nio.file.FileSystems class to create a new zip file system or to obtain a reference to an existing zip file system.
You can create a zip file system by specifying the path of the zip or JAR file in following way-

URI uri = URI.create(“jar:file:/PATH/TO/ZIPFILE”);
FileSystem fs = FileSystems.newFileSystem(uri, env);

Zipping multiple files in Java

Here is an example of zipping multiple files in Java using ZipOutputStream where each source file is added as a ZipEntry to the ZipOutputStream.

That’s all for the topic How to Zip Files 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.