Compress Files Zip Format Including subdirectories recursively
In this sample program you will see how to compress files Zip format Including subdirectories recursively using Java. We will use java.util.zip API which has very handy method to achieve this functionality. Please see sample program below:
Java Sample Program:
package com.javahonk; import java.io.BufferedInputStream; 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 CompressDataInZipDirectoryAndSubDirectory { static final int BUFFER = 2048; public static void main(String[] args) throws Exception { String zipFileNameWithPath = "C:\\JavaHonk\\zip\\DirectoryWithSubdirectory.zip"; String readFromDirctory = "C:\\JavaHonk\\zip"; File readFromDirctoryName = new File(readFromDirctory); System.out.println("Creating zip file with name : " + zipFileNameWithPath); ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileNameWithPath)); addFilesToZip(readFromDirctoryName, zipOutputStream); zipOutputStream.close(); } private static void addFilesToZip(File readFromDirctoryName, ZipOutputStream zipOutputStream) { FileInputStream fileInputStream = null; BufferedInputStream origin = null; try { File[] files = readFromDirctoryName.listFiles(); byte[] byteArray = new byte[BUFFER]; for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { addFilesToZip(files[i], zipOutputStream); continue; } System.out.println("File geting added to zip: " + files[i].getAbsolutePath()); fileInputStream = new FileInputStream(files[i].getAbsolutePath()); origin = new BufferedInputStream(fileInputStream, BUFFER); zipOutputStream.putNextEntry(new ZipEntry(files[i].getAbsolutePath())); int count; while ((count = origin.read(byteArray, 0, BUFFER)) != -1) { zipOutputStream.write(byteArray, 0, count); } } } catch (Exception exception) { exception.printStackTrace(); }finally{ try { zipOutputStream.closeEntry(); origin.close(); fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Output:
For more information about zip please refer oracle documentation here