GZIP形式でファイルを圧縮する方法

GZIP形式でファイルを圧縮する方法

Gzipは、ファイルをnix system. However, Gzip is not a ZIP tool, *it only use to compress a file into a “.gz” format, not compress several files into a single archiveで圧縮するための一般的なツールです。

GZipの例

この例では、ファイル「/home/example/file1.txt」をgzipファイル「/home/example/file1.gz」に圧縮します。

package com.example.gzip;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

public class GZipFile
{
    private static final String OUTPUT_GZIP_FILE = "/home/example/file1.gz";
    private static final String SOURCE_FILE = "/home/example/file1.txt";


    public static void main( String[] args )
    {
        GZipFile gZip = new GZipFile();
        gZip.gzipIt();
    }

    /**
     * GZip it
     * @param zipFile output GZip file location
     */
    public void gzipIt(){

     byte[] buffer = new byte[1024];

     try{

        GZIPOutputStream gzos =
            new GZIPOutputStream(new FileOutputStream(OUTPUT_GZIP_FILE));

        FileInputStream in =
            new FileInputStream(SOURCE_FILE);

        int len;
        while ((len = in.read(buffer)) > 0) {
            gzos.write(buffer, 0, len);
        }

        in.close();

        gzos.finish();
        gzos.close();

        System.out.println("Done");

    }catch(IOException ex){
       ex.printStackTrace();
    }
   }

}