java try-with-resource自動關(guān)閉
/**
* try-with-resource自動關(guān)閉
*/
public class Test04 {
? ?public static void main(String[] args) {
? ? ? ?try(FileReader reader = new FileReader("C:/a.txt");){
? ? ? ? ? ?//將打開文件的操作包在try()中 實現(xiàn)try/catch執(zhí)行完成后自動關(guān)閉文件
? ? ? ? ? ?System.out.println((char) reader.read());
? ? ? ? ? ?//{}語句塊中照常對reader操作
? ? ? ?}catch (Exception e){
? ? ? ? ? ?e.printStackTrace();
? ? ? ?}
? ? ? ?//不需要finally{.close()}
? ? ? ?try (
? ? ? ? ? ? ? ?FileReader reader1 = new FileReader("C:/a");
? ? ? ? ? ? ? ?FileReader reader2 = new FileReader("C:/b")
? ? ? ? ? ?){
? ? ? ? ? ?//可以同時打開多項
? ? ? ?}catch (Exception e){
? ? ? ? ? ?e.printStackTrace();
? ? ? ?}
? ? ? ?//try-with-resource在經(jīng)過編譯后會還原成try/catch/finally給虛擬機運行
? ?}
}
標(biāo)簽: