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 {
    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" );
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.37.154