How to create a ZIP file from an existing file in Java
What is a ZIP file?
A ZIP file is a collection of one or more files and/or folders that have been compressed into a single file for easy transfer and compression.
ZIP a single file
We can follow the steps below to create a ZIP file from an existing file.
Here, we assume the name of the file to be compressed is file.txt, and the compressed file name is file.zip.
- Check if the file exists in the filesystem. If the file doesn’t exist, then return back with the message “File does not exist”.
- Create a
FileOutputStreamobject for the ZIP file to be created. - Create an object of the
ZipOutputStreamclass. Pass theFileOutputStreamobject created in Step 2 as the parameter to the constructor. - Create a
FileInputStreamobject for the text file to be compressed. - Create a
ZipEntryobject that takes the input text file name as a constructor parameter.
Each file in the ZIP file is represented by a
ZipEntry(java.util.zip.ZipEntry). Hence, to read/write from a ZIP file,ZipEntryis used.
- Insert the
ZipEntryobject created in Step 5 into theZipOutputStreamobject, via theputNextEntrymethod. - Write the contents of the text file to the
ZipOutputStreamobject via thewritemethod. - Once all the content is written, close the
ZipEntryobject. - Close the stream objects if no more files are there to compress.
Note: Use
try-with-resourcesto autoclose the stream objects.
import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;public class Zip {public static void main(String[] args) throws IOException {String fileName = "file.txt";String zipFileName = "file.zip";if (!Files.isRegularFile(Path.of(fileName))) {System.err.println("Please provide an existing file.");return;}ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName));FileInputStream fileInputStream = new FileInputStream(fileName);ZipEntry zipEntry = new ZipEntry(fileName);zipOutputStream.putNextEntry(zipEntry);byte[] buffer = new byte[1024];int length;while ((length = fileInputStream.read(buffer)) > 0) {zipOutputStream.write(buffer, 0, length);}zipOutputStream.closeEntry();zipOutputStream.close();fileInputStream.close();}}