Complete Java Code to ZIP a Folder

By | October 22, 2015

Java Provides package which can be used to zip files into a folder using ZipOutputStream class methods. In this post; I am going to share complete java code to zip files in a folder to create a .zip file.

Explanation of Java Code for creating Zip File

The example code contains a class Zipper which has a method zipFiles which takes the name of the zip file to be created and the name of the folder containing the files as input parameters.

Based on these two parameters; the code picks each and every file from the given folder and puts into the zipoutstream as new entries and then uses write method of zipoutputstream class.

In this example code; I am calling this zipFiles method from the main method and then simply printing the output to the console which will be a success message or the exception message for success and exception cases respectively.

Java Complete Code to Zip files into a folder


public class Zipper {

public static void main(String[] args) {
String result_message=zipFiles(“D:/”,”D:/files/”);


public static String zipFiles(String zipFile, String srcDir) {
try {
File srcFile = new File(srcDir);
File[] files = srcFile.listFiles();
FileOutputStream fos = new FileOutputStream(zipFile);

ZipOutputStream zos = new ZipOutputStream(fos);

for (int i = 0; i < files.length; i++) {

// create byte buffer
byte[] buffer = new byte[1024];

FileInputStream fis = new FileInputStream(files[i]);

zos.putNextEntry(new ZipEntry(files[i].getName()));

int length;

while ((length = > 0) {
zos.write(buffer, 0, length);


// close the InputStream

catch (Exception e)
{return e.getMessage();}
return “Successfully created the zip file”+zipFile;





Ajmal Abbasi

Ajmal Hussain Abbasi is Integration Consultant By Profession with more than 7 years experience in TIBCO products. He has extensive practical knowledge of TIBCO Business Works, TIBCO Spotfire, TIBCO BE, EMS and TIBCO ActiveSpaces. He has worked on a number of highly critical integration projects in Telecom sector by using his skills in Tibco Designer, Adapters, TIBCO EMS, RV, Administrator, TIBCO BE, TIBCO ActiveSpaces etc.
Ajmal Abbasi is also experienced in developing solutions using Oracle PL/Sql, Linux and Java.
You can contact Ajmal Abbasi for Consultancy, Technical Assistance and Technical Discussions.

More Posts - Website - Facebook - LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *