File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes I/O and Streams and the fly likes Please explain me. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Please explain me." Watch "Please explain me." New topic
Author

Please explain me.

Ashok Pradhan
Ranch Hand

Joined: Dec 17, 2007
Posts: 180

In the following Program:-


i could'nt understand what is behind in these lines:-

finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
Freddy Wong
Ranch Hand

Joined: Sep 11, 2006
Posts: 959

Which part that you don't understand?

The in.close() closes the InputStream whereas the out.close() closes the OutputStream. Those statements are in the finally clause to ensure that those statements are executed. The checking for the null condition is necessary to avoid the NullPointerException if in or out is null.


SCJP 5.0, SCWCD 1.4, SCBCD 1.3, SCDJWS 1.4
My Blog
Ashok Pradhan
Ranch Hand

Joined: Dec 17, 2007
Posts: 180

if (in != null)
and
if(out!=null)
Nitesh Kant
Bartender

Joined: Feb 25, 2007
Posts: 1638

Originally posted by Ashok Pradhan:
if (in != null)
and
if(out!=null)


finally will be executed also if initialization of in and out has failed. Does that give you some clues !!!


apigee, a better way to API!
Freddy Wong
Ranch Hand

Joined: Sep 11, 2006
Posts: 959

As I've already mentioned in my above post, you need to have the null checking in order to prevent your code from having the NullPointerException.


When the code gets into line 4, and suppose that it throws an exception, it will then go to line 11 because of the finally clause, but "in" instance is still null in this case. If you don't do any null checking here, you will get NullPointerException when you try to call in.close(). Similar situation will happen in line 5. Remember, creating an instance of InputStream or OutputStream throws an exception, thus you need to either catch it or throw it.

Hopefully it's clear enough
Ashok Pradhan
Ranch Hand

Joined: Dec 17, 2007
Posts: 180

Thanks i got it!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Please explain me.
 
Similar Threads
exception
If conditional not branching correctly
files
I/O streams
Differences between FileInputStream FileReader