從jdk1.7開始,java加強了try語句的功能,它容許在try關鍵字後面跟一對圓括號,圓括號能夠聲明,初始化一個或多個資源,這裏的資源表示的是那些程序執行完畢以後須要關閉的資源,例如:(IO流,數據庫鏈接,網絡鏈接等),try語句在改語句結束的時候會自動的關閉這些資源。看代碼java
1 try ( FileInputStream fileInputStream = new FileInputStream(new File(""))) { 2 //TODO 3 } catch (FileNotFoundException e) { 4 e.printStackTrace(); 5 } catch (IOException e) { 6 e.printStackTrace(); 7 }
不再用再finally裏面去寫關閉了數據庫
1 FileInputStream fileInputStream = null; 2 try { 3 fileInputStream = new FileInputStream(new File("")) 4 } catch (FileNotFoundException e) { 5 e.printStackTrace(); 6 } catch (IOException e) { 7 e.printStackTrace(); 8 } finally { 9 try { 10 fileInputStream.close(); 11 } catch (IOException e) { 12 e.printStackTrace(); 13 } 14 }