GZIP Compresses a given file into a new file. - Java File Path IO

Java examples for File Path IO:GZIP

Description

GZIP Compresses a given file into a new file.

Demo Code


//package com.java2s;
import java.io.*;

import java.util.zip.GZIPOutputStream;

public class Main {
    public static final int BUFF_SIZE = 2048;

    /**/* w  w  w . j  av  a2s . c  om*/
     * Compresses a given file into a new file.  This method will refuse to overwrite an existing file
     *
     * @param toCompress      the file you want to compress.
     * @param destinationFile the the file you want to compress into.
     * @throws java.io.IOException if there was a problem or if you were trying to overwrite an existing file.
     */
    public static void compressFile(final File toCompress,
            final File destinationFile) throws IOException {
        streamToCompressedFile(new FileInputStream(toCompress),
                destinationFile);
    }

    /**
     * Takes in InputStream and compresses it into a given file.  This method will not overwrite an existing file.
     *
     * @param istream         the stream to compress and write out
     * @param destinationFile the file you want to put the compressed stream into.
     * @throws IOException if there
     */
    public static void streamToCompressedFile(final InputStream istream,
            final File destinationFile) throws IOException {
        if (destinationFile.exists()) {
            throw new IOException("Refusing to overwrite an existing file.");
        }

        OutputStream gzStream = null;
        InputStream biStream = null;
        try {
            gzStream = new GZIPOutputStream(new BufferedOutputStream(
                    new FileOutputStream(destinationFile)), BUFF_SIZE);
            biStream = new BufferedInputStream(istream, BUFF_SIZE);
            transferStream(biStream, gzStream);
        } finally {
            if (gzStream != null) {
                gzStream.close();
            }
            if (biStream != null) {
                biStream.close();
            }
        }
    }

    /**
     * Transfers an InputStream to an OutputStream it is up to the job of the caller to close the streams.
     *
     * @param istream
     * @param ostream
     * @throws IOException
     */
    protected static void transferStream(final InputStream istream,
            final OutputStream ostream) throws IOException {
        final byte[] inBuf = new byte[BUFF_SIZE];
        int readBytes = istream.read(inBuf);
        while (readBytes >= 0) {
            ostream.write(inBuf, 0, readBytes);
            readBytes = istream.read(inBuf);
        }
    }
}

Related Tutorials