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 Outputr.close();}catch(IOException e) {// display a message about the errorif (r != null) {try {r.close();}// tried to close but couldn't anyway!// should inform the user if the data was important...catch(Exception ignoreMe) {}}}Note how the declaration of the FileReader has moved outside the try block soit can be accessed in the catch block. But this is still problematic, for tworeasons:• If there were several catch blocks, the close code would need to be repeated ineach, making it easy to make an error or even miss a spot.• If a non-IOException were thrown, the file would not be closed! For example,a NullPointerException would cause a problem.A better approach would be to use a finally clause to do the closing:FileReader r = null;try {r = new FileReader("somefile.txt");// read some text from the file// NOTE: No close() here!}catch(IOException e) {// display a message about the error}finally {if (r != null) {try {r.close();}// tried to close but couldn't anyway!// should inform the user if the data was important...catch(Exception ignoreMe) {}}}This ensures that no matter what happens, we at least try to close the file.But what happens if we start using filters, and for some reason a filter does notopen completely?Java Input and Output -60© 1996-2003 jGuru.com. All Rights Reserved.

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

Saved successfully!

Ooh no, something went wrong!