demo以下html
/** * 利用Try-Catch-Finally管理資源(舊的代碼風格) * * @throws IOException */ @Test public void test1() throws IOException { String filepath = "D:\\gui-config.json"; BufferedReader br = null; String curline; try { br = new BufferedReader(new FileReader(filepath)); while ((curline = br.readLine()) != null) { System.out.println(curline); } } catch (FileNotFoundException e) { throw new FileNotFoundException("文件xxx不存在,請檢查後重試。"); // trturn xxx; } catch (IOException e) { throw new IOException("文件xxx讀取異常。"); } finally { try { if (br != null) { br.close(); } } catch (IOException e) { throw new IOException("關閉流異常。"); } } }
該try-with資源語句是try聲明瞭一個或多個資源聲明。一個資源是程序與它完成後,必須關閉的對象。該try-with資源語句確保每一個資源在發言結束時關閉。java
任何實現的java.lang.AutoCloseable對象(包括實現的全部對象)java.io.Closeable均可以用做資源。json
demo以下oracle
@Test public void test2() throws IOException { String filepath = "D:\\gui-config.json"; try ( FileReader fileReader = new FileReader(filepath); BufferedReader br = new BufferedReader(fileReader) ) { String curline = null; while ((curline = br.readLine()) != null) { System.out.println(curline); } } } // FileReader 和 BufferedReader 均實現了 AutoCloseable 接口
自定義 AutoCloseable 實現類curl
public class AutoCloseTestModel implements AutoCloseable { @Override public void close() throws Exception { System.out.println("資源管理"); } public void run(boolean flag) { if (flag) { System.out.println("業務處理"); } else { System.out.println("出現異常"); throw new RuntimeException("自定義RuntimeException"); } } } @Test public void test3() throws Exception { try (AutoCloseTestModel autoCloseTestModel = new AutoCloseTestModel()) { autoCloseTestModel.run(false); } }
oracle java 教程 - try-with-resources語句ide