java try-with-resource自动关闭
/**
* try-with-resource自动关闭
*/
public class Test04 {
public static void main(String[] args) {
try(FileReader reader = new FileReader("C:/a.txt");){
//将打开文件的操作包在try()中 实现try/catch执行完成后自动关闭文件
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在经过编译后会还原成try/catch/finally给虚拟机运行
}
}