美文网首页
JAVA7 try-with-resource语法糖

JAVA7 try-with-resource语法糖

作者: 沙夏cc | 来源:发表于2019-03-22 15:13 被阅读0次

    在 JDK 7 之前,资源需要手动关闭。

    Charset charset = Charset.forName("US-ASCII");
    String s = ...;
    BufferedWriter writer = null;
    try {
        writer = Files.newBufferedWriter(file, charset);
        writer.write(s, 0, s.length());
    } catch (IOException x) {
        System.err.format("IOException: %s%n", x);
    } finally {
        if (writer != null) writer.close();
    }
    

    JDK7中,大大化简了这步操作,可以使用如下代码

    public class Demo {    
        public static void main(String[] args) {
            try(Resource res = new Resource()) {
                res.doSome();
            } catch(Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    
    class Resource implements AutoCloseable {
        void doSome() {
            System.out.println("do something");
        }
        @Override
        public void close() throws Exception {
            System.out.println("resource is closed");
        }
    }
    

    JDK9中,又有新的提升

    // New and improved try-with-resources statement in JDK 9
    try (resource1;
         resource2) {
        // Use of resource1 and resource 2.
    }
    

    不过使用面较小,就不细致讨论了。

    相关文章

      网友评论

          本文标题:JAVA7 try-with-resource语法糖

          本文链接:https://www.haomeiwen.com/subject/oofrvqtx.html