集册 Java实例教程 将输入流gzip压缩到压缩后的输出流。

将输入流gzip压缩到压缩后的输出流。

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

515
将输入流gzip压缩到压缩后的输出流。
/**
n o w    j a v a  . c o m 提供 
**/


//package com.nowjava;

import java.io.Closeable;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;


import java.util.zip.GZIPOutputStream;


public class Main {

    /**

     * gzip an input stream to a gzipped output stream. You need to close streams manually.

     * @param is input stream

     * @param gzippedOutputStream gzipped output stream

     * @throws IOException

     */

    public static void gzip(InputStream is,

            GZIPOutputStream gzippedOutputStream) throws IOException {// 来自 时代Java公众号

        byte[] buffer = new byte[1024];

        int len = -1;

        while ((len = is.read(buffer)) != -1) {

            gzippedOutputStream.write(buffer, 0, len);

        }

    }


    /**

     * gzip an input stream to a gzipped file. You need to close streams manually.

     * @param is input stream

     * @param gzippedFile gzipped file

     * @throws IOException

     */

    public static void gzip(InputStream is, File gzippedFile)

            throws IOException {

        GZIPOutputStream gos = null;

        try {

            gos = new GZIPOutputStream(new FileOutputStream(gzippedFile));

            byte[] buffer = new byte[1024];

            int len = -1;

            while ((len = is.read(buffer)) != -1) {

                gos.write(buffer, 0, len);

            }

        } finally {

            close(gos);

        }

    }


    /**

     * gzip a file to a gzipped file

     * @param srcFile file to be gzipped

     * @param gzippedFile target gzipped file

     * @throws IOException

     */

    public static void gzip(File srcFile, File gzippedFile)

            throws IOException {

        GZIPOutputStream gos = null;

        FileInputStream fis = null;

        try {

            gos = new GZIPOutputStream(new FileOutputStream(gzippedFile));

            fis = new FileInputStream(srcFile);

            byte[] buffer = new byte[1024];

            int len = -1;

            while ((len = fi
展开阅读全文