Filter IO Streams


Filter IO Streams

Filter IO Streams:
Filter IO Streams comes under Stream facing Streams, where the Filter IO Streams depends upon an intermediate Java IO Stream to perform the primary read and write operation over source or destination. Filter IO Stream provides a clean way of implementing ‘computing logic’ over the data read or write by the primary IO Stream.



Example of a Filter IO Stream :-

Below is an example of a Filter IO Stream, which uses a primary IO Stream Reader to READ content from a file and then the Processing Logic reverses the content before handing it to the caller. 

  

public class ReverseReader extends FilterReader
{

 protected ReverseReader(Reader in) {
  super(in);
  // TODO Auto-generated constructor stub
 }
 
 @Override
 public int read() throws IOException {
  // Reads Single Character, hence NO need to REVERSE 
  return super.read();
 }
 
 @Override
 public int read(char[] b) throws IOException {
  // We don't need to process here because internally it calls read(char[] b, int off, int len)
  // and hence will be processed by the same.
  return super.read(b);
 }
 
 @Override
 public int read(char[] b, int off, int len) throws IOException {
  int bytesRead = super.read(b, off, len);
  int maxByteArrayPosition = bytesRead == 0?bytesRead:bytesRead-1;
  char byteHolder;
  
  for(int count = off; count < ((maxByteArrayPosition+off)-count); count++)
  {
   byteHolder = b[count];
   b[count] = b[(maxByteArrayPosition+off) - count];
   b[(maxByteArrayPosition+off) - count] = byteHolder;
  }
  
  return bytesRead;
 }  

<< File IO Stream Buffered IO Stream >>

No comments:

Post a Comment