Compress Files Zip Format Java
We will create sample program to compress multiple files in Zip format using Java program. Java API gives java.util.zip package doing the zip compatible format data compression also it gives API which can be use to create, modify and read files in Zip and GZIP format. Please have example below:
Note: This program will compress all files in current directory and to handle zip for sub-directory we will cover in next demo program.
package com.javahonk; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class CompressDataInZipCurrentDirectory { static final int BUFFER = 2048; public static void main(String argv[]) { ZipOutputStream zipOutputStream = null; BufferedInputStream origin = null; try { File file = new File("C:\\JavaHonk\\zip\\Test.zip"); if (!file.exists()) { file.createNewFile(); } FileOutputStream destination = new FileOutputStream("C:\\JavaHonk\\zip\\Test.zip"); zipOutputStream = new ZipOutputStream(new BufferedOutputStream(destination)); byte data[] = new byte[BUFFER]; // Get list of files from current directory File file2 = new File("c:\\JavaHonk\\zip\\New"); String files[] = file2.list(); for (int i = 0; i < files.length; i++) { System.out.println("Adding file name: " + files[i]); FileInputStream fileInputStream = new FileInputStream(file2.getAbsolutePath()+ File.separator + files[i]); origin = new BufferedInputStream(fileInputStream, BUFFER); ZipEntry entry = new ZipEntry(files[i]); zipOutputStream.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { zipOutputStream.write(data, 0, count); } } System.out.println("Desitnation file name: "+file.getName()); } catch (Exception e) { e.printStackTrace(); }finally{ try { zipOutputStream.close(); origin.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Output:
For more information about zip please refer oracle documentation here