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 a Folder to create a .zip file containing all files from that folder.
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;
}}