java資源關(guān)閉使用try-with-resource替換

JDK7之后,Java資源關(guān)閉新的語法:try-with-resources語句

傳統(tǒng)寫法代碼

public void readFile() throws FileNotFoundException {
        FileReader fr = null;
        BufferedReader br = null;
        try{
            fr = new FileReader("d:/input.txt");
            br = new BufferedReader(fr);
            String s = "";
            while((s = br.readLine()) != null){
                System.out.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                br.close();
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

try with resource寫法

public void readFile() throws FileNotFoundException {

        try(
                FileReader fr = new FileReader("d:/input.txt");
                BufferedReader br = new BufferedReader(fr)
        ){
            String s = "";
            while((s = br.readLine()) != null){
                System.out.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容