Java Zip Folder zipFolder(String sourceDir, String destDir, String name)

Here you can find the source of zipFolder(String sourceDir, String destDir, String name)

Description

zip Folder

License

Apache License

Declaration

public static void zipFolder(String sourceDir, String destDir, String name) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class Main {
    public static void zipFolder(String sourceDir, String destDir, String name) throws IOException {
        FileOutputStream fos = new FileOutputStream(destDir + "/" + name + ".zip");
        ZipOutputStream zipOut = new ZipOutputStream(fos);
        File fileToZip = new File(sourceDir);

        zipFile(fileToZip, fileToZip.getName(), zipOut);
        zipOut.close();//  w ww. j  av a  2 s.c  o  m
        fos.close();

    }

    private static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException {

        if (fileToZip.isHidden()) {
            return;
        }
        if (fileToZip.isDirectory()) {
            File[] children = fileToZip.listFiles();
            for (File childFile : children) {
                zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
            }
            return;
        }
        FileInputStream fis = new FileInputStream(fileToZip);
        ZipEntry zipEntry = new ZipEntry(fileName);
        zipOut.putNextEntry(zipEntry);
        byte[] bytes = new byte[1024];
        int length;
        while ((length = fis.read(bytes)) >= 0) {
            zipOut.write(bytes, 0, length);
        }
        fis.close();
    }
}

Related

  1. zipFolder(File srcFolder, File destZipFile, boolean zipOnlySrcFolderContentsAndNotSrcFolder)
  2. zipFolder(File srcFolder, String destZipFile)
  3. zipFolder(final File directory, final String path, final ZipOutputStream out)
  4. zipFolder(final File srcFolder, final OutputStream out)
  5. zipFolder(final String srcFolder, final String destZipFile)
  6. zipFolder(String sourceFolder, String target)
  7. zipFolder(String srcFolder, String destZipFile)
  8. zipFolder(String srcFolder, String destZipFile)
  9. zipFolder(String srcFolder, String destZipFile)