Code to create Zip file using Java .

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Java_Classes;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 *
 * @author snlkjha
 */
public class Zip {

    public static void zipFolder(String srcFolder) throws Exception {
        FileOutputStream fileWriter = new FileOutputStream(srcFolder + ".zip");
        ZipOutputStream zip = new ZipOutputStream(fileWriter);
        addFolderToZip("", srcFolder, zip);
        zip.flush();
        zip.close();
    }

    private static void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws Exception {
        File folder = new File(srcFolder);
        for (String fileName : folder.list()) {
            if (path.equals("")) {
                addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
            } else {
                addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip);
            }
        }
    }

    private static void addFileToZip(String path, String srcFile, ZipOutputStream zip) throws Exception {

        File folder = new File(srcFile);
        if (folder.isDirectory()) {
            addFolderToZip(path, srcFile, zip);
        } else {
            byte[] buf = new byte[1024];
            int len;
            FileInputStream in = new FileInputStream(srcFile);
            zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
            while ((len = in.read(buf)) > 0) {
                zip.write(buf, 0, len);
            }
        }
    }
}

Call : Zip.zipFolder(folderpath);
output : folderpath.zip will be created.
Example: if zipFolder="F:/Testing";
Output :F:/Testing.zip

Alternative : Download Zip.jar

a. Add to project library folder
b. import zip.Zip; in ur program;
c. Call : Zip.zipFolder(folderpath);
output : folderpath.zip will be created.
Example: if zipFolder="F:/Testing";
Output :F:/Testing.zip

Popular posts from this blog

8 Bit Plane Slicing of an image in Image Processing

Code to upload multiple files simultaneously using JSP, Servlet .

STRING PALINDROME USING STACK AND QUEUE