LoginSignup
9
9

More than 5 years have passed since last update.

Java GZIP圧縮(単体のファイルを扱う場合には使いやすい)

Last updated at Posted at 2016-02-11

はじめに

事前に準備する外部ライブラリ等はありません。
JavaSEに含まれるjava.util.zip.GZIPOutputStreamクラスを使用します。

実装例

サンプルでは、動作確認しやすいようにmainメソッドで実行できるようにしてあります。

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

/**
 *
 * @author tool-taro.com
 */
public class GZIPTest {

    public static void main(String[] args) throws IOException {

        //圧縮対象のデータ(今回は文字列)
        String source = "これはテストです。\n以上。";
        //圧縮後のファイルの保存場所
        String outputFilePath = "output.txt.gz";
        //圧縮前にバイト配列に置き換える際のエンコーディング
        String encoding = "UTF-8";

        GZIPOutputStream gout = null;

        try {
            gout = new GZIPOutputStream(new FileOutputStream(outputFilePath));
            gout.write(source.getBytes(encoding));
        }
        finally {
            if (gout != null) {
                try {
                    gout.close();
                }
                catch (IOException e) {
                }
            }
        }
    }
}

動作確認

$ javac GZIPTest.java
$ java GZIPTest

生成されたファイルの解凍結果と、
無題.png
解凍後のテキスト内容です。
無題2.png

環境

  • 開発

    • Windows 10 Pro
    • JDK 1.8.0_112
    • NetBeans IDE 8.2
  • 動作検証

    • CentOS Linux release 7.2
    • JDK 1.8.0_112

Webツールも公開しています。
Web便利ツール@ツールタロウ

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9