Zipping a folder which contains subfolders

Here's the code for creating the ZIP archive. Created archive preserves original directory structure (if any).

public static void addDirToZipArchive(ZipOutputStream zos, File fileToZip, String parrentDirectoryName) throws Exception {
    if (fileToZip == null || !fileToZip.exists()) {
        return;
    }

    String zipEntryName = fileToZip.getName();
    if (parrentDirectoryName!=null && !parrentDirectoryName.isEmpty()) {
        zipEntryName = parrentDirectoryName + "/" + fileToZip.getName();
    }

    if (fileToZip.isDirectory()) {
        System.out.println("+" + zipEntryName);
        for (File file : fileToZip.listFiles()) {
            addDirToZipArchive(zos, file, zipEntryName);
        }
    } else {
        System.out.println("   " + zipEntryName);
        byte[] buffer = new byte[1024];
        FileInputStream fis = new FileInputStream(fileToZip);
        zos.putNextEntry(new ZipEntry(zipEntryName));
        int length;
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
        zos.closeEntry();
        fis.close();
    }
}

Don't forget to close output streams after calling this method. Here's the example:

public static void main(String[] args) throws Exception {
    FileOutputStream fos = new FileOutputStream("C:\\Users\\vebrpav\\archive.zip");
    ZipOutputStream zos = new ZipOutputStream(fos);
    addDirToZipArchive(zos, new File("C:\\Users\\vebrpav\\Downloads\\"), null);
    zos.flush();
    fos.flush();
    zos.close();
    fos.close();
}

Simply you can use this library Zeroturnaround Zip library
Then you will zip your folder just a one line:

ZipUtil.pack(new File("D:\\sourceFolder\\"), new File("D:\\generatedZipFile.zip"));

You need to check if the file is a directory because you can't pass directories to the zip method.

Take a look at this page which shows how you can recursively zip a given directory.

Tags:

Java

Zip