Monday, March 30, 2015

Right way to Close InputStream and OutputStream in Java

Right way to Close InputStream and OutputStream in Java

For some unknown reasons many Java programmers are not very comfortable with IO package. I don't know why, but I have found them much more comfortable with java.lang and java.util than java.io. One possible reason of this could be that, writing IO code require a bit of C++ like programming, which involves doing clean-up, releasing resources once done etc. Since Java made coding a lot easier by taking care of memory management, unknowingly it also introduced bad practice of not releasing resource after use e.g. database connections, socket connection, files, directory, printers, scanners or any other scarce resource. The laziness of just doing work and forget everything is very easy, because of this many Java programmer never bother about doing clean-up. This habit is most visible in programmers who have never done system programming using C or C++. Since IO requires you to deal with streams, channels, and file descriptors, which need to be closed properly, Java developer find it uneasy to deal with. On other day, I asked one candidate to write code for copying content of one file to another without using copy() method or a third-party library. Though he managed to write the code, he made a common mistake, he was not closing streams properly. It's important to close streams, to release file descriptor held by this class, as its limited resource and used in both socket connection and file handling. A serious resource leak may result in file descriptor exception as well. Before moving ahead, let's see the part of  the code candidate wrote for copying file from one directory to another directory in Java without using any third-party library.

No comments:

Post a Comment