Java Zip Files addToZip(File file, ZipOutputStream out, String folder)

Here you can find the source of addToZip(File file, ZipOutputStream out, String folder)

Description

Zip the specified file or folder.

License

Apache License

Parameter

Parameter Description
file The file or folder to zip
out The destination zip stream
folder The current folder

Exception

Parameter Description
IOException If an IO error occurs.

Declaration

private static void addToZip(File file, ZipOutputStream out, String folder) throws IOException 

Method Source Code


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

import java.io.BufferedInputStream;

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   www . j  av a 2s  .  c  o  m
     * Size of internal buffer.
     */
    private static final int BUFFER = 2048;

    /**
     * Zip the specified file or folder.
     *
     * @param file   The file or folder to zip
     * @param out    The destination zip stream
     * @param folder The current folder
     *
     * @throws IOException If an IO error occurs.
     */
    private static void addToZip(File file, ZipOutputStream out, String folder) throws IOException {
        // Directory
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File f : files) {
                    addToZip(f, out, (folder != null ? folder + file.getName() : file.getName()) + "/");
                }
            }

            // File
        } else {
            byte[] data = new byte[BUFFER];
            BufferedInputStream origin = null;
            try {
                FileInputStream fi = new FileInputStream(file);
                origin = new BufferedInputStream(fi, BUFFER);
                ZipEntry entry = new ZipEntry(folder != null ? folder + file.getName() : file.getName());
                out.putNextEntry(entry);
                int count;
                while ((count = origin.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
            } finally {
                if (origin != null) {
                    origin.close();
                }
            }
        }
    }
}

Related

  1. addFileToZip(ZipOutputStream zos, File file, File rootDir)
  2. addFileToZipOutputStream(File file, ZipOutputStream zipOs)
  3. addToZip(byte[] zip, String file, String fileName)
  4. addToZip(File directoryToZip, File file, ZipOutputStream zos)
  5. addToZip(File f, int truncate, ZipOutputStream os, byte[] buff)
  6. addToZip(File input, String entryName, ZipOutputStream zos, boolean withHidden, Set excludeEntries)
  7. addToZip(String path, String srcFile, ZipOutputStream zip)
  8. addToZip(String path, String srcFile, ZipOutputStream zip)
  9. addToZip(String[] sourceFiles, ZipOutputStream output)