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 OutputUTFDataFormatExceptionWriteAbortedExceptionAn attempt to read a UTF-8 stream failed dueto malformed UTF-8 content. This can occurwhen calling the readUTF() method ofDataInputStream or RandomAccessFile.Thrown while reading a serialized object streamif the stream was only partially written becausean ObjectStreamException was thrown whilewriting it.Closing StreamsThe most difficult thing to do with regard to I/O is to properly close a stream.There are several subtle problems. The main concerns are:• where should I put the close() call?• how do I deal with exceptions thrown when opening filters?• what happens if a filter's close() throws an exception?Let's start with the basic close() handling case first. The basic issue is, "wheredo I put the close() to ensure my file will be really be closed?" A first attemptmight look like:// ... CAUTION ...WRONG WAY TO DO THINGS...try {FileReader r = new FileReader("somefile.txt");// read some text from the filer.close();}catch(IOException e) {// display a message about the error}This approach is too simple. The file will be closed only if there are no exceptionsthrown between the file opening and the attempt to close it. A second attemptmight be:// ... CAUTION ...WRONG WAY TO DO THINGS...FileReader r = null;try {r = new FileReader("somefile.txt");// read some text from the file© 1996-2003 jGuru.com. All Rights Reserved. Java Input and Output -59

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

Saved successfully!

Ooh no, something went wrong!