Takes in InputStream and GZIP compresses it into a given file. - Java File Path IO

Java examples for File Path IO:GZIP

Description

Takes in InputStream and GZIP compresses it into a given file.

Demo Code


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

import java.util.zip.GZIPOutputStream;

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

    /**// www  . ja  v  a 2 s .  com
     * 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