Guava CountingOutputStreamを使用する
1概要
このチュートリアルでは、
CountingOutputStream
クラスとその使用方法について説明します。
このクラスは
Apache Commons
などの一般的なライブラリにあります。
Google Guava
。 Guavaライブラリでの実装に焦点を合わせています。
2
CountingOutputStream
2.1. Mavenの依存関係
CountingOutputStream
は、GoogleのGuavaパッケージの一部です。
pom.xml
に依存関係を追加することから始めましょう。
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>24.1-jre</version>
</dependency>
依存関係の最新バージョンはhttps://search.maven.org/classic/#search%7C1%7Cg%3A%22com.google.guava%22%20AND%20a%3A%22guava%22[]で確認できます。ここに]。
2.2. クラス詳細
このクラスはhttps://docs.oracle.com/javase/7/docs/api/java/io/FilterOutputStream.html?is-external=true[
java.io.FilterOutputStream
]を拡張し、
write()
および
closeをオーバーライドします。 ()
メソッド、および新しいメソッド
getCount()
を提供します。
コンストラクターは入力パラメーターとして別の
OutputStream
オブジェクトを取ります。 ** データの書き込み中、クラスはこの
OutputStream
に書き込まれたバイト数をカウントします。
カウントを取得するために、単に
getCount()
を呼び出して現在のバイト数を返すことができます。
----/** ** Returns the number of bytes written. ** /public long getCount() {
return count;
}
----
3使用事例
実用的なユースケースで
CountingOutputStream
を使用しましょう。例として、コードを実行可能にするためにコードをJUnitテストに入れます。
今回のケースでは、
OutputStream
にデータを書き込み、上限の
MAX
バイトに達したかどうかを確認します。
制限に達したら、例外をスローして実行を中断します。
public class GuavaCountingOutputStreamTest {
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()
を提供しています。
最後に、いつものように、議論中に使用されたコードはhttps://github.com/eugenp/tutorials/tree/master/guava[over on GitHub]にあります。