This post demonstrates a simple example for how to compress your file and add to the ZIP file. Java has built-in API java.util.zip for compressing the files in ZIP format. It is very simple to read the files from your disk and writing to the destination ZIP file. It is straight forward. The steps involved for writing to ZIP is:
- Read files using FileInputStream
- Then add the files to ZipEntry which is used for adding the list of files which are part of zip file
- Finally output the zip file by using the ZipOutputStream class
Lets look at the example:
package javabeat.net.core; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class CompressZipExample { public static void main(String[] args) { byte[] buffer = new byte[1024]; try { FileOutputStream fileOutput = new FileOutputStream("SampleFile.zip"); ZipOutputStream zipOutput = new ZipOutputStream(fileOutput); //Add a file entry to zip ZipEntry zipEntry = new ZipEntry("TestFile.txt"); zipOutput.putNextEntry(zipEntry); //Read the file from the given path FileInputStream fileInput = new FileInputStream("TestFile.txt"); int length; while ((length = fileInput.read(buffer)) > 0) { zipOutput.write(buffer, 0, length); } fileInput.close(); zipOutput.closeEntry(); zipOutput.close(); System.out.println("Files are added to zip!!"); } catch (IOException ex) { ex.printStackTrace(); } } }