1. 概述

本文将介绍 Guava 库中的 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>32.1.3-jre</version>
</dependency>

最新版本可在此查看:Maven Central

2.2 类详解

该类继承自 java.io.FilterOutputStream,重写了 write()close() 方法,并新增了 getCount() 方法。

构造函数接收一个 OutputStream 对象作为参数。在写入数据时,类会统计写入到这个 OutputStream 的字节数。

要获取计数值,只需调用 getCount() 方法即可返回当前字节数:

/** 返回已写入的字节数 */
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("写入限制已触发");
            }
        }
    }
}

4. 总结

本文快速介绍了 CountingOutputStream 类及其用法。该类通过 getCount() 方法提供了统计已写入字节数的功能,简单实用。

完整代码示例可在 GitHub 获取。


原始标题:Using Guava CountingOutputStream