If you encounter problems when using the stream, you may need to debug the function.
The Java I/O framework is implemented based on a series of connected streams. This design enhances component reusability and makes Locating Errors difficult. When you insert your own debugging stream into the stream, error locating becomes easier. For example, the CountingOutputStream class reports the number of bytes it has written. This function is useful when flush is used to cause loss of bytes.
The following is an example of using CountingOutputStream:
Package com. generationjava. io;
Import java. io. IOException;
Import java. io. OutputStream;
Import java. io. FilterOutputStream;
Public class CountingOutputStream extends FilterOutputStream {
Private int count;
Public CountingOutputStream (OutputStream out ){
Super (out );
}
Public void write (byte [] B) throws IOException {
Count + = B. length;
Super. write (B );
}
Public void write (byte [] B, int off, int len) throws IOException {
Count + = len;
Super. write (B, off, len );
}
Public void write (int B) throws IOException {
Count + = 2;
Super. write (B );
}
Public int getCount (){
Return this. count;
}
}
In the following small piece of code, there is a simple error-the stream is neither flush nor closed.
File file = ...;
Byte [] data = ...;
OutputStream out = new BufferedOutputStream (
New FileOutputStream (file)
);
Out. write (data );
Insert CountingOutputStream to find the problem:
File file = ...;
Byte [] data = ...;
CountingOutputStream cos = new CountingOutputStream (
New FileOutputStream (file)
);
OutputStream out = new BufferedOutputStream (cos );
Out. write (data );
System. err. println ("Bytes written:" + cos. getCount ());
If this code is output:
Bytes Written: 0
Then we can quickly find out that the problem lies in BufferedOutputStream, which does not send anything to the FileOutputStream stream. This method makes it easier to find that the cached stream does not flush its buffer.
Although this example is too simplified, it still proves the effectiveness of stream debugging. When there are four or more streams in the chain, inserting and moving the debugging stream will help developers find problems faster.