Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

10.10. Measuring Stream Traffic

10.10.1. Problem

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

10.10.2. 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

10.10.3. 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 {
    FileInputStream fis = new FileInputStream( test );
    countStream = new CountingOutputStream( fis );
    String contents = IOUtils.toString( countStream );
} catch( IOException ioe ) {
    System.out.println( "Error reading bytes from file." );
} finally {
    IOUtils.closeQuietly( countStream );
}
if( countStream != null ) {
    int bytesRead = countStream.getCount( );
    System.out.println( "Read " + bytesRead + " bytes from test.dat" );
}

Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.