Java Zip Files addFileToZip(String path, String srcFile, ZipOutputStream zip)

Here you can find the source of addFileToZip(String path, String srcFile, ZipOutputStream zip)

Description

add File To Zip

License

Open Source License

Declaration

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

Method Source Code


//package com.java2s;
/*/* w w w . ja va  2  s  . co m*/
 * Copyright (c) 2002-2006 The European Bioinformatics Institute, and others.
 * All rights reserved. Please see the file LICENSE
 * in the root directory of this distribution.
 */

import java.io.*;

import java.util.zip.*;

public class Main {
    static private void addFileToZip(String path, String srcFile, ZipOutputStream zip) throws IOException {

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

    /**
     * Zip the subdirectory and exclude already zipped files
     * @param path
     * @param srcFolder
     * @param zip
     * @param includeFullPath
     * @throws java.io.IOException
     */
    static private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip, boolean includeFullPath)
            throws IOException {
        File folder = new File(srcFolder);

        for (String fileName : folder.list()) {
            if (path.equals("") && !fileName.endsWith(".zip")) {
                if (includeFullPath) {
                    addFileToZip(folder.toString(), srcFolder + "/" + fileName, zip);
                } else {
                    addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
                }
            } else if (!fileName.endsWith(".zip")) {
                addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip);
            }
        }
    }
}

Related

  1. addFileToZip(final String pathInsideZip, final File fileToZip, final ZipOutputStream outZip)
  2. addFileToZip(int skipprefix, File file, ZipOutputStream zipper)
  3. addFileToZip(String path, File srcFile, ZipOutputStream zip, boolean flag)
  4. addFileToZip(String path, File srcFile, ZipOutputStream zip, String destZipFile)
  5. addFileToZip(String path, String srcFile, ZipOutputStream zip)
  6. addFileToZip(ZipOutputStream out, InputStream in, String entry)
  7. addFileToZip(ZipOutputStream zipOutputStream, File file, String basePath)
  8. addFileToZip(ZipOutputStream zipOutputStream, String path, byte[] bytes)
  9. addFileToZip(ZipOutputStream zos, File file, File rootDir)