Guava CountingOutputStreamを使用する

Guava CountingOutputStreamの使用

 

1. 概要

このチュートリアルでは、CountingOutputStreamクラスとその使用方法を見ていきます。

このクラスは、Apache CommonsGoogle Guavaなどの一般的なライブラリにあります。 Guavaライブラリでの実装に焦点を当てます。

2. CountingOutputStream

2.1. メーベン依存

CountingOutputStreamはGoogleのGuavaパッケージの一部です。

pom.xmlに依存関係を追加することから始めましょう:


    com.google.guava
    guava
    24.1-jre

依存関係の最新バージョンはhereで確認できます。

2.2. クラスの詳細

このクラスはjava.io.FilterOutputStreamを拡張し、write()メソッドとclose()メソッドをオーバーライドし、新しいメソッドgetCount()を提供します。

コンストラクターは、別のOutputStreamオブジェクトを入力パラメーターとして受け取ります。 While writing data, the class then counts the number of bytes written into this OutputStream.

カウントを取得するには、getCount()を呼び出して、現在のバイト数を返すだけです。

/** Returns the number of bytes written. */
public long getCount() {
    return count;
}

3. 使用事例

実際のユースケースでCountingOutputStreamを使用してみましょう。 例として、コードをJUnitテストに入れて実行可能にします。

この例では、OutputStreamにデータを書き込み、MAXバイトの制限に達しているかどうかを確認します。

制限に達したら、例外をスローして実行を中断します。

public class GuavaCountingOutputStreamUnitTest {
    static int MAX = 5;

    @Test(expected = RuntimeException.class)
    public void givenData_whenCountReachesLimit_thenThrowException()
      throws Exception {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        CountingOutputStream cos = new CountingOutputStream(out);

        byte[] data = new byte[1024];
        ByteArrayInputStream in = new ByteArrayInputStream(data);

        int b;
        while ((b = in.read()) != -1) {
            cos.write(b);
            if (cos.getCount() >= MAX) {
                throw new RuntimeException("Write limit reached");
            }
        }
    }
}

4. 結論

この簡単な記事では、CountingOutputStreamクラスとその使用法について説明しました。 このクラスは、これまでにOutputStreamに書き込まれたバイト数を返す追加のメソッドgetCount()を提供します。

最後に、いつものように、議論中に使用されたコードはover on GitHubで見つけることができます。