Java Zip File zip(final String sourceFileDir, final String zipFile)

Here you can find the source of zip(final String sourceFileDir, final String zipFile)

Description

Zip it

License

Apache License

Parameter

Parameter Description
zipFile output ZIP file location
sourceFileDir a parameter

Exception

Parameter Description
IOException an exception
FileNotFoundException an exception

Declaration

public static void zip(final String sourceFileDir, final String zipFile)
        throws FileNotFoundException, IOException 

Method Source Code


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

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import java.util.ArrayList;

import java.util.List;
import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class Main {
    /**//from ww w.  j a  v  a 2 s .  c o  m
      * Zip it
      * @param zipFile output ZIP file location
     * @param sourceFileDir 
     * @throws IOException 
     * @throws FileNotFoundException 
      */
    public static void zip(final String sourceFileDir, final String zipFile)
            throws FileNotFoundException, IOException {
        final byte[] buffer = new byte[1024];
        try (final FileOutputStream fos = new FileOutputStream(zipFile);
                final ZipOutputStream zos = new ZipOutputStream(fos)) {
            final List<File> fileList = new ArrayList<>();
            generateFileList(new File(sourceFileDir), fileList);
            for (final File file : fileList) {
                final ZipEntry ze = new ZipEntry(file.getName());
                zos.putNextEntry(ze);
                try (final FileInputStream in = new FileInputStream(file)) {
                    int len;
                    while ((len = in.read(buffer)) > 0) {
                        zos.write(buffer, 0, len);
                    }
                }
            }
        }
    }

    /**
     * Traverse a directory and get all files,
     * and add the file into fileList  
     * @param node file or directory
     */
    private static void generateFileList(final File node, final List<File> fileList) {
        //add file only
        if (node.isFile()) {
            fileList.add(node);
        }
        if (node.isDirectory()) {
            final String[] subNote = node.list();
            for (final String filename : subNote) {
                generateFileList(new File(node, filename), fileList);
            }
        }
    }
}

Related

  1. zip(final File zipFile, final File... files)
  2. zip(final File zipFile, final File[] files)
  3. zip(final File[] filesToZip, final File zipFile)
  4. zip(final Map files)
  5. zip(final String fileName, final byte[] fileContent)
  6. zip(InputStream is)
  7. zip(InputStream is, String dataFileName, File zipFile)
  8. zip(OutputStream outputStream, File targetFile)
  9. zip(String data, String fileName)