You need to keep track
of the number of bytes read from an
InputStream
or written to an
OutputStream
.
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
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" ); }
18.118.37.154