集册 Java实例教程 GZIP将给定文件压缩为新文件。

GZIP将给定文件压缩为新文件。

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

654
GZIP将给定文件压缩为新文件。


//package com.nowjava;

import java.io.*;/**nowjava**/


import java.util.zip.GZIPOutputStream;


public class Main {

    public static final int BUFF_SIZE = 2048;


    /**

     * 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),//from nowjava

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