JAVA7 try-with-resource语法糖

2019-03-22  本文已影响0人  沙夏cc

在 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.
}

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

上一篇下一篇

猜你喜欢

热点阅读