Complete Java Code to ZIP a Folder

By | October 22, 2015

Java Provides java.util.zip 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

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 Zipper {

public static void main(String[] args) {
String result_message=zipFiles(“D:/zipped_folder.zip”,”D:/files/”);
System.out.println(result_message);

}

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 = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}

zos.closeEntry();

// close the InputStream
fis.close();

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

}

 

 

 

Ajmal Abbasi

Ajmal Hussain Abbasi is a TIBCO Consultant By Profession with more than 6 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 *