gzip an input stream to a gzipped output stream. - Java File Path IO

Java examples for File Path IO:GZIP

Description

gzip an input stream to a gzipped output stream.

Demo Code


//package com.java2s;
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 {
    /**//  ww  w .j  av  a 2 s . c o  m
     * 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 {
        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 = fis.read(buffer)) != -1) {
                gos.write(buffer, 0, len);
            }
        } finally {
            close(fis);
            close(gos);
        }
    }

    private static void close(Closeable io) {
        if (io != null) {
            try {
                io.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            io = null;
        }
    }
}

Related Tutorials