What is the best way to emulate try-with-resources in Java 6?

后端 未结 3 1493
感情败类
感情败类 2021-01-17 18:18

It turns out that almost nobody closes resources in Java correctly. Programmers either do not use try-finally block at all, or just put resource.close()

3条回答
  •  旧巷少年郎
    2021-01-17 19:07

    If your only problem with IOUtils.closeQuietly is that it ignores exceptions on OutputStreams, then you can either simply call close() on them, or create your own utility class which automatically treats the two differently, like this:

    public static void close(Closeable resource)
    {
        try
        {
            resource.close();
        }
        catch(Exception e)
        {
            //swallow exception
        }
    }
    
    public static void close(OutputStream o)
    {
        //throw any exceptions
        o.close();
    }
    

    The correct overloaded method will be selected at compile time in all common situations, although if you're passing OutputStreams around as Closeables then you'll have to change this to do a dynamic instanceof check to make sure OutputStreams always throw exceptions.

提交回复
热议问题