In this post we will see how to compress files in java using ZIP format.
Java provides a complete package java.util.zip to perform compression/decompression.
Steps to compress files in ZIP format
1. Create a ZipOutputStream using a FileOutputStream
1 2 |
FileOutputStream fileOutputStream = new FileOutputStream("C:\\kscodes\\after\\ZippedFileTest.zip"); ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream)); |
2. Read all the Files that need to be zipped.
1 2 |
File inputDir = new File("C:\\kscodes\\before"); String listOfFiles[] = inputDir.list(); |
3. Iterate each file and use ZipEntry to add each file to Zip
1 2 |
ZipEntry entry = new ZipEntry(fileName); zipOutputStream.putNextEntry(entry); |
Example
Lets zip the files from the below folder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
package com.kscodes.sampleproject; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class CompressFileExample { public static void main(String[] args) { try { byte buffer[] = new byte[2048]; FileOutputStream fileOutputStream = new FileOutputStream( "C:\\kscodes\\after\\ZippedFileTest.zip"); ZipOutputStream zipOutputStream = new ZipOutputStream( new BufferedOutputStream(fileOutputStream)); File inputDir = new File("C:\\kscodes\\before"); String listOfFiles[] = inputDir.list(); BufferedInputStream bufferedInputStream = null; for (String fileName : listOfFiles) { System.out.println("Adding File to zip: " + fileName); FileInputStream fileInputStream = new FileInputStream(new File( inputDir, fileName)); bufferedInputStream = new BufferedInputStream(fileInputStream); ZipEntry entry = new ZipEntry(fileName); zipOutputStream.putNextEntry(entry); int count; while ((count = bufferedInputStream.read(buffer)) != -1) { zipOutputStream.write(buffer, 0, count); } bufferedInputStream.close(); } zipOutputStream.close(); System.out.println("File Zipped!!!!!"); } catch (Exception e) { e.printStackTrace(); } } } |
Output
1 2 3 4 5 |
Adding File to zip: Java_Tutorials.doc Adding File to zip: Privacy Policy.txt Adding File to zip: Test.txt Adding File to zip: Tips&Tricks.txt File Zipped!!!!! |