Java Zip File zipFile(File sourceFile)

Here you can find the source of zipFile(File sourceFile)

Description

Compress a file or recursively compress all files of a folder.

License

Open Source License

Parameter

Parameter Description
sourceFile a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static File zipFile(File sourceFile) throws IOException 

Method Source Code

//package com.java2s;
/*********************************************************************************
 * The contents of this file are subject to the Common Public Attribution
 * License Version 1.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.openemm.org/cpal1.html. The License is based on the Mozilla
 * Public License Version 1.1 but Sections 14 and 15 have been added to cover
 * use of software over a computer network and provide for limited attribution
 * for the Original Developer. In addition, Exhibit A has been modified to be
 * consistent with Exhibit B.//www . j  av a2 s  . co m
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 *
 * The Original Code is OpenEMM.
 * The Original Developer is the Initial Developer.
 * The Initial Developer of the Original Code is AGNITAS AG. All portions of
 * the code written by AGNITAS AG are Copyright (c) 2007 AGNITAS AG. All Rights
 * Reserved.
 *
 * Contributor(s): AGNITAS AG.
 ********************************************************************************/

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;

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

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class Main {
    /**
     * Compress a file or recursively compress all files of a folder.
     * The compressed file will be placed in the same directory as the data.
     * 
     * @param sourceFile
     * @return
     * @throws IOException
     */
    public static File zipFile(File sourceFile) throws IOException {
        File zippedFile = new File(sourceFile.getAbsolutePath() + ".zip");
        zipFile(sourceFile, zippedFile);
        return zippedFile;
    }

    /**
     * Compress a file or recursively compress all files of a folder.
     * 
     * @param sourceFile
     * @param destinationZipFile
     * @throws IOException
     */
    public static void zipFile(File sourceFile, File destinationZipFile) throws IOException {
        ZipOutputStream zipOutputStream = null;

        if (!sourceFile.exists())
            throw new IOException("SourceFile does not exist");

        if (destinationZipFile.exists())
            throw new IOException("DestinationFile already exists");

        try {
            zipOutputStream = openNewZipOutputStream(destinationZipFile);

            addFileToOpenZipFileStream(sourceFile, zipOutputStream);

            closeZipOutputStream(zipOutputStream);
            zipOutputStream = null;
        } catch (IOException e) {
            if (destinationZipFile.exists()) {
                if (zipOutputStream != null) {
                    try {
                        zipOutputStream.close();
                    } catch (Exception ex) {
                    }
                    zipOutputStream = null;
                }
                destinationZipFile.delete();
            }
            throw e;
        } finally {
            if (zipOutputStream != null) {
                try {
                    zipOutputStream.close();
                } catch (Exception e) {
                }
                zipOutputStream = null;
            }
        }
    }

    /**
     * Open new ZipOutputStream based on a file to write into
     * 
     * @param destinationZipFile
     * @return
     * @throws IOException
     */
    public static ZipOutputStream openNewZipOutputStream(File destinationZipFile) throws IOException {
        if (destinationZipFile.exists())
            throw new IOException("DestinationFile already exists");
        else if (!destinationZipFile.getParentFile().exists())
            throw new IOException("DestinationDirectory does not exist");

        try {
            return new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destinationZipFile)));
        } catch (IOException e) {
            if (destinationZipFile.exists()) {
                destinationZipFile.delete();
            }
            throw e;
        }
    }

    /**
     * Open new ZipOutputStream based on a OutputStream to write into
     * 
     * @param destinationZipStream
     * @return
     * @throws IOException
     */
    public static ZipOutputStream openNewZipOutputStream(OutputStream destinationZipStream) throws IOException {
        if (destinationZipStream == null)
            throw new IOException("DestinationStream is missing");

        return new ZipOutputStream(new BufferedOutputStream(destinationZipStream));
    }

    /**
     * Compress a file or recursively compress all files of a folder.
     * This starts a new relative path.
     * 
     * @param sourceFile
     * @param destinationZipFileSream
     * @throws IOException
     */
    public static void addFileToOpenZipFileStream(File sourceFile, ZipOutputStream destinationZipFileSream)
            throws IOException {
        addFileToOpenZipFileStream(sourceFile, File.separator, destinationZipFileSream);
    }

    /**
     * Compress a file or recursively compress all files of a folder.
     * 
     * @param sourceFile
     * @param destinationZipFileSream
     * @throws IOException
     */
    public static void addFileToOpenZipFileStream(File sourceFile, String relativeDirPath,
            ZipOutputStream destinationZipFileSream) throws IOException {
        BufferedInputStream bufferedFileInputStream = null;

        if (!sourceFile.exists())
            throw new IOException("SourceFile does not exist");

        if (destinationZipFileSream == null)
            throw new IOException("DestinationStream is not ready");

        if (relativeDirPath == null || (!relativeDirPath.endsWith("/") && !relativeDirPath.endsWith("\\")))
            throw new IOException("RelativeDirPath is invalid");

        try {
            if (!sourceFile.isDirectory()) {
                ZipEntry entry = new ZipEntry(relativeDirPath + sourceFile.getName());
                entry.setTime(sourceFile.lastModified());
                destinationZipFileSream.putNextEntry(entry);

                bufferedFileInputStream = new BufferedInputStream(new FileInputStream(sourceFile));
                byte[] bufferArray = new byte[1024];
                int byteBufferFillLength = bufferedFileInputStream.read(bufferArray);
                while (byteBufferFillLength > -1) {
                    destinationZipFileSream.write(bufferArray, 0, byteBufferFillLength);
                    byteBufferFillLength = bufferedFileInputStream.read(bufferArray);
                }
                bufferedFileInputStream.close();
                bufferedFileInputStream = null;

                destinationZipFileSream.flush();
                destinationZipFileSream.closeEntry();
            } else {
                for (File sourceSubFile : sourceFile.listFiles()) {
                    addFileToOpenZipFileStream(sourceSubFile,
                            relativeDirPath + sourceFile.getName() + File.separator, destinationZipFileSream);
                }
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (bufferedFileInputStream != null) {
                try {
                    bufferedFileInputStream.close();
                } catch (Exception e) {
                }
                bufferedFileInputStream = null;
            }
        }
    }

    /**
     * Close an open ZipOutputStream
     * 
     * @param zipOutputStream
     * @throws IOException
     */
    public static void closeZipOutputStream(ZipOutputStream zipOutputStream) throws IOException {
        try {
            zipOutputStream.finish();
            zipOutputStream.flush();
            zipOutputStream.close();
            zipOutputStream = null;
        } catch (IOException e) {
            throw e;
        } finally {
            if (zipOutputStream != null) {
                try {
                    zipOutputStream.close();
                } catch (Exception e) {
                }
                zipOutputStream = null;
            }
        }
    }
}

Related

  1. zipFile(File root, String outFileFullName, String[] suffixs, String[] nameMatche, String[] nameNotMatche)
  2. zipFile(File source, File dest)
  3. zipFile(File source, File target)
  4. zipFile(File source, File target)
  5. zipFile(File source, String basePath, ZipOutputStream zos)
  6. zipFile(File zipfile, ZipOutputStream zos, String name)
  7. zipFile(final File source)
  8. zipFile(final File target, final ZipOutputStream zip, final File file, final String path)
  9. zipFile(String filedir, String zippath)