8/25/2010

Automatic Resource Management in java 7

最近 Java 7 build 105版本加入一個 Automatic Resource Management 特性,基本上,就是try-with-resources觀念。try block中所使用的resource將會自動被關閉不管正常執行完或發生錯誤,日後不需要再手動關掉resource物件,。

FEATURE SUMMARY: A *resource* is as an object that must be closed manually, such as a java.io.InputStream, OutputStream, Reader, Writer, Formatter; java.nio.Channel;java.net.socket; java.sql.Connection, Statement, ResultSet, or java.awt.Graphics. The *automatic resource management statement* is a form of the try statement that declares one or more resources. The scope of these resource declarations is limited to the statement. When the statement completes, whether normally or abruptly, all of its resources are closed automatically.

之前的寫法

[java] static void copy(String src, String dest) throws IOException { InputStream in = new FileInputStream(src); try { OutputStream out = new FileOutputStream(dest); try { byte[] buf = new byte[8 * 1024]; int n; while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); } finally { out.close(); } } finally { in.close(); } } [/java]

之後的寫法

[java] static void copy(String src, String dest) throws IOException { try (InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest)) { byte[] buf = new byte[8192]; int n; while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); } } [/java]

不過感覺上沒有太多吸引人的地方,而且每個java版本支援會有問題發生,還是三思再說

No comments:

Post a Comment