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 Outputfollowing scenario:Writer realFile = new Writer("a.txt");Writer filter2 = new TabToSpaceWriter(realFile);Writer filter1 = new UppercaseWriter(filter2);filter1.write("Hello!");realFile.close();Think about what might happen if either TabToSpaceWriter orUppercaseWriter decides to hold all its output until you close them (perhaps forbuffering purposes). If you close the real file before closing the filters, there is noway to pump the output to the real file.When you close a filter, it flushes any output it might have been storing to itsoutputDelegate, then calls close() on the outputDelegate. The proper code forthe above would beWriter realFile = new Writer("a.txt");Writer filter2 = new TabToSpaceWriter(realFile);Writer filter1 = new UppercaseWriter(filter2);filter1.write("Hello!");filter1.close();// flushes filter1// calls filter2.close()// flushes filter2// calls realFile.close()// close filter2 (mark closed)// close filter1 (mark closed)Note: You do not need to close the inner filters, as the outer filter's close()method automatically calls the inner filter's close().We will see later, when we discuss exceptions, that closing a file is a bit moredifficult than it may seem. The important concept to note at this point is the orderin which you must close the filters -- close the outermost filter first!Common Filters Provided with JavaJava comes with several useful filters that can be used "right out of the box".These filters perform various tasks such as buffering to make I/O more efficient,encoding primitive types, and writing the state of entire Java objects.Java Input and Output -22© 1996-2003 jGuru.com. All Rights Reserved.

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

Saved successfully!

Ooh no, something went wrong!