Automatic resource management comes with Java 7, which will automatically handle this. Until then, objects such as OutputStream , InputStream and others implement the Closeable interface with Java 5. I suggest you provide a utility method for closing them safely. These methods usually contain exceptions, so be sure to use them only when you want to ignore exceptions (for example, in the finally method). For example:
public class IOUtils { public static void safeClose(Closeable c) { try { if (c != null) c.close(); } catch (IOException e) { } } }
Please note that the close() method can be called several times, if it is already closed, subsequent calls will have no effect, therefore they also cause a call to close during the normal operation of the try block, where the exception will not be ignored. From the documentation of Closeable.close :
If the thread is already closed, calling this method has no effect
Close the output stream in a regular code stream, and the safeClose method will only work if something failed in the try block:
FileOutputStream out = null; try { out = new FileOutputStream("myfile.txt");
krock Jul 22 2018-10-22T00: 00Z
source share