Zipping a folder which contains subfolders

public static void main(String argv[]) {
    try {
        String date = new java.text.SimpleDateFormat("MM-dd-yyyy")
                .format(new java.util.Date());
        File inFolder = new File("Output/" + date + "_4D");
        File outFolder = new File("Output/" + date + "_4D" + ".zip");
        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
                new FileOutputStream(outFolder)));
        BufferedInputStream in = null;
        byte[] data = new byte[1000];
        String files[] = inFolder.list();
        for (int i = 0; i < files.length; i++) {
            in = new BufferedInputStream(new FileInputStream(
                    inFolder.getPath() + "/" + files[i]), 1000);
            out.putNextEntry(new ZipEntry(files[i]));
            int count;
            while ((count =, 0, 1000)) != -1) {
                out.write(data, 0, count);
    } catch (Exception e) {

I'm trying to zip a folder which contains subfolders. Trying to zip the folder named 10-18-2010_4D.The above program ends with the following exception. Please advise on how to clear the issue. Output\10-18-2010_4D\4D (Access is denied)
    at Method)
    at<init>(Unknown Source)
    at<init>(Unknown Source)
    at ZipFile.main(

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.

Windows: Zip (Compress) Multiple Files - Help Pages, How do I zip a folder and its contents in Linux? Stack Overflow Public questions and answers; Teams Private questions and answers for your team; Enterprise Private self-hosted questions and answers for your enterprise; Talent Hire technical talent

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()) {

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

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\\");
    ZipOutputStream zos = new ZipOutputStream(fos);
    addDirToZipArchive(zos, new File("C:\\Users\\vebrpav\\Downloads\\"), null);

How to zip a folder – WeTransfer Support, 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  Hi, I have a folder that contains a few sub-folders. I would like to zip that folder and KEEP the subfolders. What it does at the moment is taking all the files within the subfolders and zipping them | The UNIX and Linux Forums

private void zipFiles (ArrayList listWithFiles, String zipName) {
    try {

        byte[] buffer = new byte[1024];

        // create object of FileOutputStream
        FileOutputStream fout = new FileOutputStream(zipName);

        // create object of ZipOutputStream from FileOutputStream
        ZipOutputStream zout = new ZipOutputStream(fout);

        for (String currentFile : listWithFiles) {

            // create object of FileInputStream for source file
            FileInputStream fin = new FileInputStream(currentFile);

            // add files to ZIP
            zout.putNextEntry(new ZipEntry(currentFile ));

            // write file content
            int length;

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


            // close the InputStream

        // close the ZipOutputStream
    } catch (IOException ioe) {
        System.out.println("IOException :" + ioe);

How to Zip a Folder in Ubuntu & Other Linux [Terminal & GUI], "Recursively" means that the zip file will include subfolders of the given folder, the subfolders of those folders, and so on. How can I create folder and subfolder in sharepoint using rest Powershell script to move files and folders including subfolders from one location to another older than x days Zip folder located in %appdata% using vbscript

I would include the ant task for zipping - it is way easier to work with.

The task class can be found here: (use it programatically)

Zipping a folder which contains subfolders, Hi, Have a look here: Compress Folders with C# and the SharpZipLib[^]. I am probably biased, but I would use ZPAQ. It supports dedupe, so it should give you better compression than zip, which compresses each file separately. Use method 1 (default) for fast compression or 2 for better but slower compression with no lo

Here is what I've written. This example keeps the structure of the files and by that, avoid the duplicate entry exception.

     * Compress a directory to ZIP file including subdirectories
     * @param directoryToCompress directory to zip
     * @param outputDirectory     where to place the compress file
    public void zipDirectory(File directoryToCompress, File outputDirectory){
        try {
            FileOutputStream dest = new FileOutputStream(new File(outputDirectory, directoryToCompress.getName() + ".zip"));
            ZipOutputStream zipOutputStream = new ZipOutputStream(dest);

            zipDirectoryHelper(directoryToCompress, directoryToCompress, zipOutputStream);
        } catch (Exception e) {

    private void zipDirectoryHelper(File rootDirectory, File currentDirectory, ZipOutputStream out) throws Exception {
        byte[] data = new byte[2048];

        File[] files = currentDirectory.listFiles();
        if (files == null) {
          // no files were found or this is not a directory

        } else {
            for (File file : files) {
                if (file.isDirectory()) {
                    zipDirectoryHelper(rootDirectory, file, out);
                } else {
                    FileInputStream fi = new FileInputStream(file);
                    // creating structure and avoiding duplicate file names
                    String name = file.getAbsolutePath().replace(rootDirectory.getAbsolutePath(), "");

                    ZipEntry entry = new ZipEntry(name);
                    int count;
                    BufferedInputStream origin = new BufferedInputStream(fi,2048);
                    while ((count =, 0 , 2048)) != -1){
                        out.write(data, 0, count);


Zipping folders and their contents into a .zip file in Linux, How do I store folder information only for subfolders? Start WinZip, find the folder containing the files you want to zip in the Files pane and open it (10October) Click the box in the bottom left of the Files pane to select all files (and subfolders) in the open folder. Click the Add to zip button. To zip a folder using Drag and Drop, you can: Drag the folder you wish to zip onto an existing Zip file Drag the folder you wish to zip onto the WinZip desktop shortcut Drag the folder you wish to zip onto an open WinZip window.

Zipping a folder which contains subfolders, There are numerous ways to zip files in folders. The resulting Zip file will maintain the level2 folder/file structure and would include the subfolders below. folder\subfolder1\zip1 folder\subfolder2\zip2 folder\subfolder3\zip3 folder\subfolder4\zip4 I would like to have the contents of each zipfile extracted within it containting folder. The zip files and the subfolders have different names.

How do I control the folder information WinZip stores in a Zip file , If you want the zip file to contain only contents , not child1/contents , then do this: for dir in */; do ( cd "$dir" && zip -r ../"${dir%/}".zip . ) done. I'm trying to zip a folder which contains subfolders. Trying to zip the folder named 10-18-2010_4D.The above program ends with the following exception. Please advise on how to clear the issue.

How to Zip files with their folder information – WinZip, It uses a proprietary network protocol that has low overhead (compared to TCP/IP​) and on the fly compression. Maybe ask them for a free of  VBA code to Zip and Unzip files and folders Posted on August 21, 2017 April 25, 2020 by Excel Off The Grid Recently, I have been working on a project which requires the zipping and unzipping files and folders.

  • The folder name in the exception and the one which you mentioned are different.
  • possible duplicate of directories in a zip file when using
  • I think @dogbane is correct. I ran your code using a directory containing only files, and it worked as intended. As soon as I added a nested directoyr, I got the FNF (Access is Denied) exception.
  • Can you give some points about why we must prefer ant task for zipping?
  • it's done in 3 lines of code, and it works. Compare to the above.
  • @Bozho I could find many jar files in the recent version of Ant. which one should be used for Zipping folders?
  • Except if you want to implement zip compression in your own application
  • @LGAP - see my update. @jassuncao - you can use it programatically