Effective Java~9. try-with-resource 优先于 try-catch
try-finally 語(yǔ)句是保證資源正確關(guān)閉的最佳方式,但是當(dāng)添加多個(gè)資源時(shí),情況會(huì)變?cè)?/p> // try-finally is ugly when used with more than one resource! static void copy(String src, String dst) throws IOException {InputStream in = new FileInputStream(src);try {OutputStream out = new FileOutputStream(dst);try {byte[] buf = new byte[BUFFER_SIZE];int n;while ((n = in.read(buf)) >= 0)out.write(buf, 0, n);} finally {out.close();}} finally {in.close();} }
????????當(dāng) Java 7 引入了 try-with-resources 語(yǔ)句時(shí),所有這些問(wèn)題一下子都得到了解決。要使用這個(gè)構(gòu)造,資源必須實(shí)現(xiàn) AutoCloseable 接口
// try-with-resources on multiple resources - short and sweet static void copy(String src, String dst) throws IOException {try (InputStream in = new FileInputStream(src);OutputStream out = new FileOutputStream(dst)) {byte[] buf = new byte[BUFFER_SIZE];int n;while ((n = in.read(buf)) >= 0)out.write(buf, 0, n);} }try-with-resources 語(yǔ)句中添加 catch 子句,就像在常規(guī)的 try-finally 語(yǔ)句中一樣
// try-with-resources with a catch clause static String firstLineOfFile(String path, String defaultVal) {try (BufferedReader br = new BufferedReader(new FileReader(path))) {return br.readLine();} catch (IOException e) {return defaultVal;} }總結(jié)
以上是生活随笔為你收集整理的Effective Java~9. try-with-resource 优先于 try-catch的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Replace Data Value w
- 下一篇: 设计模式之禅--思维导图