13.07.2015 Views

I/O Fundamentals

I/O Fundamentals

I/O Fundamentals

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Java Input and OutputThink about the following code:// ... CAUTION ... WRONG WAY TO DO THINGS ...Reader r = new BufferedReader(new FileReader("somefile.txt"));Suppose BufferedReader cannot obtain enough memory to allocate its buffer. Itwill throw an OutOfMemoryException which exits the constructor. But whathappens to the FileReader? It has been opened!A safer way to deal with filter nesting is to track all streams. For example// A SAFER OPEN/CLOSE SCENARIOFileReader fr = null;BufferedReader br = null;TabToSpaceReader ttsr = null; // assuming you defined such asfilter...try {ttr = new TabToSpaceReader(br = new BufferedReader(fr = new FileReader("somefile.txt")));// read some text from ttr}finally {if (ttr != null) {try {ttr.close();br = null;fr = null;}catch(Exception ignoreMe) {}ttr = null;}if (br != null) {try {br.close();fr = null;}catch(Exception ignoreMe) {}br = null;}if (fr != null) {try {fr.close();}catch(Exception ignoreMe) {}fr = null;}© 1996-2003 jGuru.com. All Rights Reserved. Java Input and Output -61

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

Saved successfully!

Ooh no, something went wrong!