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 = in.read(data, 0, 1000)) != -1) {
                out.write(data, 0, count);
            }
            out.closeEntry();
        }
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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.

java.io.FileNotFoundException: Output\10-18-2010_4D\4D (Access is denied)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at ZipFile.main(ZipFile.java:17)

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

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

            zout.closeEntry();

            // close the InputStream
            fin.close();
        }

        // close the ZipOutputStream
        zout.close();
    } 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: org.apache.tools.ant.taskdefs.Zip (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);
            zipOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
    }

    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);
                    out.putNextEntry(entry);
                    int count;
                    BufferedInputStream origin = new BufferedInputStream(fi,2048);
                    while ((count = origin.read(data, 0 , 2048)) != -1){
                        out.write(data, 0, count);
                    }
                    origin.close();
                }
            }
        }

    }

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.

Comments
  • The folder name in the exception and the one which you mentioned are different.
  • possible duplicate of directories in a zip file when using java.util.zip.ZipOutputStream
  • 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