Wednesday, August 15, 2007

Java5 added Closeable and I did not even notice!

I stumpled upon some code written by a wise colleague of mine. The code use the new (well, actually not so knew anymore) java.io.Closeable interface, to add a static helper method which can be used in finally blocks to close resources. Here is the code:
import java.io.Closeable;
import java.io.IOException;
public class ResourceUtil {
public static void closeResource(Closeable resource) {
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
//no operation
}
}
}
}

Now, this kind of ResourceUtil class is not at all new to me. I am used to writing such one up too. What has changed is the use of Closeable. Before that interface, I wrote one such method for InputStream, one for OutputStream, files, sockets, ...

Now we only need commons-lang to implement the class shown above :-)

No comments: