13.07.2015 Views

I/O Fundamentals

I/O Fundamentals

I/O Fundamentals

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Java Input and OutputDelegation is useful in cases where• we don't know how to perform a task, or• it would be more efficient to have a different object perform the task, or• code for the exact task has already been written in another class that is not oursuperclass, or• we want the basic implementation of another class's method(s) but need tomodify them slightly (but cannot subclass for some reason)The last case is the one that we will concentrate on now. Java uses delegation tochange the way a delegate reads and writes a stream.Java's Use of I/O DelegatesJava uses delegates to do the "real I/O" in a filter. Each filter's constructor has anargument that is a Reader, Writer, InputStream, or OutputStream. When thefilter is asked to perform I/O, it delegates to this argument.FilterInputStream(InputStream inputDelegate)FilterOutputStream(OutputStream outputDelegate)FilterReader(Reader inputDelegate)FilterWriter(Writer outputDelegate)Each read() request first calls the inputDelegate's read() to get the data. Thedata is then modified (translating or removing characters, perhaps) and returned.Each write() request first modifies the output data, then passes it to theoutputDelegate's write() method.Note that FilterInputStream is a subclass of InputStream! This means thatyou could pass a FilterInputStream to a FilterInputStream, chaining filtersto perform a series of translations. Think of the benefit. Suppose we wanted toapply filters that uppercase all characters and translate tabs to spaces. Supposefurther that sometimes we only want to perform one of these filtering operations.Without Java's ability to "nest" filters, we would require a class for each type ofoutput:• UppercaseTabToSpaceWriter• UppercaseWriter• TabToSpaceWriterJava Input and Output -20© 1996-2003 jGuru.com. All Rights Reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!