10.10. Measuring Stream Traffic

Problem

You need to keep track of the number of bytes read from an InputStream or written to an OutputStream.

Solution

Use a CountingInputStream or CountingOutputStream to keep track of the number of bytes written to a stream. The following example uses a CountingOutputStream to keep track of the number of bytes written to a FileOutputStream :

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.CountingOutputStream;
import java.io.*;

File test = new File( "test.dat" );
CountingOutputStream countStream = null;

try {
    FileOutputStream fos = new FileOutputStream( test );
    countStream = new CountingOutputStream( fos );
    countStream.write( "Hello".getBytes( ) );
} catch( IOException ioe ) {
    System.out.println( "Error writing bytes to file." );
} finally {
    IOUtils.closeQuietly( countStream );
}

if( countStream != null ) {
    int bytesWritten = countStream.getCount( );
    System.out.println( "Wrote " + bytesWritten + " bytes to test.dat" );
}

This previous example wrapped a FileOutputStream with a CountingOutputStream, producing the following console output:

Wrote 5 bytes to test.dat

Discussion

CountingInputStream wraps an InputStream and getCount( ) provides a running tally of total bytes read. The following example demonstrates CountingInputStream:

import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.CountingOutputStream; import java.io.*; File test = new File( "test.dat" ); CountingInputStream countStream = null; try ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.