集册 Java实例教程 GZIP将一个压缩文件解压缩为另一个文件。

GZIP将一个压缩文件解压缩为另一个文件。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

579
GZIP将一个压缩文件解压缩为另一个文件。


//package com.nowjava;

import java.io.*;

import java.util.zip.GZIPInputStream;/** from 时代Java - nowjava.com**/


public class Main {

    public static final int BUFF_SIZE = 2048;


    /**

     * Decompresses one gzipped file into another file.

     *

     * @param toDecompress

     * @param destinationFile

     * @throws IOException if there was a problem.

     */

    public static void decompressFile(final File toDecompress,

            final File destinationFile) throws IOException {


        if (destinationFile.exists()) {

            throw new IOException("Refusing to overwrite an existing file.");

        }


        InputStream istream = null;

        OutputStream ostream = null;

        try {

        /** from 
        n o w    j a v a  . c o m**/

            ostream = new BufferedOutputStream(new FileOutputStream(

                    destinationFile), BUFF_SIZE);

            istream = getCompressedFileAsStream(toDecompress);

            transferStream(istream, ostream);

        } finally {

            if (istream != null) {

                istream.close();

            }

            if (ostream != null) {

                ostream.close();

            }

        }

    }


    /**

     * gets an InputStream from a file that is gzip compressed.

     *

     * @param file

     * @return

     * @throws IOException

     */

    public static InputStream getCompressedFileAsStream(final File file)

            throws IOException {

        return new GZIPInputStream(new BufferedInputStream(

                new FileInputStream(file)));

    }


    /**

     * 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 i
展开阅读全文