[Java] try-with-resources 說明, 如何自動 close BufferedReader 等 IO 物件
每次用到 BufferReader , IO 等物件時候,通常都要寫 很多 try catch 去確保 物件有 close ,免得memory leak issue,像是以下程式碼 請看下面這個例子: package idv.jacky.ironman4; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Day20Example { public static void main (String[] args) throws IOException { BufferedReader br = null ; try { br = new BufferedReader( new FileReader( "c:\\temp.txt" )); String line; while ((line = br.readLine()) != null ) System.out.println(line); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null ) br.close(); } } } 上面的例子,可以看到程式碼非常多的巢結構,可以改成以下的寫法 請看下面這個例子: package idv.jacky.ironman4; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Day20Example { public static void main (String[] args) throws IOException { try ( BufferedReader br = new BufferedReader( new FileReader( "c:\\temp.txt...