Java Zip Directory addDirToArchive(ZipOutputStream zos, String path, File initialDir)

Here you can find the source of addDirToArchive(ZipOutputStream zos, String path, File initialDir)

Description

Add a directory to a ZIP archive

License

Open Source License

Parameter

Parameter Description
zos a parameter
srcDir a parameter

Declaration

public static void addDirToArchive(ZipOutputStream zos, String path, File initialDir) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;

import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Main {
    /**/*from   w  w  w  .  j av  a 2 s  .c  om*/
     * Add a directory to a ZIP archive
     * 
     * @param zos
     * @param srcDir
     */
    public static void addDirToArchive(ZipOutputStream zos, String path, File initialDir) {

        File srcDir = new File(path);
        File[] files = srcDir.listFiles();

        for (int i = 0; i < files.length; i++) {
            try {

                // Get the relative path
                String relativePath = initialDir.toURI().relativize(files[i].toURI()).getPath();

                // Create file or folder
                zos.putNextEntry(new ZipEntry(relativePath));

                // Check if empty directory
                boolean emptyDir = files[i].isDirectory() && files[i].length() == 0;

                // Write file or folder with content
                if (!emptyDir) {

                    FileInputStream fis = new FileInputStream(files[i]);

                    // create byte buffer
                    byte[] buffer = new byte[1024];

                    int length;

                    // Write the content
                    while ((length = fis.read(buffer)) > 0) {
                        zos.write(buffer, 0, length);
                    }

                    fis.close();
                } else {
                    // Write empty directory
                    zos.write(new byte[0], 0, 0);
                }

                zos.closeEntry();

            } catch (IOException ioe) {
                ioe.printStackTrace();
            }

            // if the file is directory, use recursion
            if (files[i].isDirectory()) {
                addDirToArchive(zos, files[i].getPath(), initialDir);
            }
        }
    }
}

Related

  1. addDirectoryToZip(ZipOutputStream out, File dir, String prefix)
  2. addDirectoryToZip(ZipOutputStream zipOutputStream, File dirToZip, String basePath, File fileToExclude)
  3. addDirectoryToZip(ZipOutputStream zipOutputStream, String dirName)
  4. addDirToArchive(ZipOutputStream zop, File srcFile)
  5. addDirToArchive(ZipOutputStream zos, File srcFile)
  6. zip(File dir, File base, ZipOutputStream out)
  7. zip(File dir, ZipOutputStream out, String prefix)
  8. zip(File dir2zip, File zipFile)
  9. zip(File directory, File base, ZipOutputStream zos)