1. Overview
In this tutorial, we’re going to look at the CountingOutputStream class and how to use it.
The class can be found in popular libraries like Apache Commons or Google Guava. We’re going focus on the implementation in the Guava library.
2. CountingOutputStream
2.1. Maven Dependency
CountingOutputStream is part of Google’s Guava package.
Let’s start by adding the dependency to the pom.xml:
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>24.1-jre</version> </dependency>
The latest version of the dependency can be checked here.
2.2. Class Details
The class extends java.io.FilterOutputStream, overrides the write() and close() methods, and provides the new method getCount().
The constructor takes another OutputStream object as an input parameter. While writing data, the class then counts the number of bytes written into this OutputStream.
In order to get the count, we can simply call getCount() to return the current number of bytes:
/** Returns the number of bytes written. */ public long getCount() { return count; }
3. Use Case
Let’s use CountingOutputStream in a practical use case. For the sake of example, we’re going to put the code into a JUnit test to make it executable.
In our case, we’re going to write data to an OutputStream and check if we have reached a limit of MAX bytes.
Once we reach the limit, we want to break the execution by throwing an exception:
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. Conclusion
In this quick article, we’ve looked at the CountingOutputStream class and its usage. The class provides the additional method getCount() that returns the number of bytes written to the OutputStream so far.
Finally, as always, the code used during the discussion can be found over on GitHub.