Create a New ZIP Archive File in Java
Compress data into a shareable encrypted or unencrypted ZIP archive using APIs.
Join the DZone community and get the full member experience.Join For Free
Creating a ZIP file is one of the best ways to compress large amounts of data into an easily shareable format. The format was originally developed in 1989 for use by PKWARE Inc.’s PKZIP utility and was quickly picked and implemented by other software utilities, such as Microsoft and Apple. Since then, the term “zipping a file” has become synonymous with file compression.
There are many advantages to zipping files, with the most obvious reason being to optimize file storage. If you have an abundance of infrequently used files, they can be archived into a single, easily located ZIP file. Other advantages of zipping files include the ability to securely email a previously unmanageable amount of information to a client, as well as the easy transference to USB flash drives.
The following APIs will show you how to create a new ZIP archive file in Java, providing options for both encrypted and unencrypted archives.
Our first step in the process is to install the Maven SDK by adding a reference to the repository in pom.xml:
Then, add a reference to the dependency:
After this, we can add the imports to the top of our controller and configure the API Key; to retrieve your personal API key, head to the Cloudmersive website to register for a free account.
Now that we’ve completed these steps, we are ready to call our API functions. The first API will produce a straightforward, unencrypted archive file, with compression allowance for up to ten files. Once you have input the target files, we can call the function with the following code:
If you need to share the archive with a client or partner, you may want to encrypt the file to ensure the information is secure. The following API will perform the same zipping of the file, but will add encryption and password protection:
For the encrypted zip function to run smoothly, you will need to input these additional parameters:
- Password - the password to place on the Zip file; the longer the password, the more secure.
- Encryption algorithm – possible values for the encryption algorithm are AES-256 (recommended), AES-128, and PK-Zip (not recommended; legacy, weak encryption algorithm). Default is AES-256.
And that will do it! By the end of the process, you will have a storage-friendly and easily shareable ZIP file.
Opinions expressed by DZone contributors are their own.