try-with-resources 语句,称为 ARM 块(Automatic Resource Management) ,自动资源管理,所有实现了Closeable接口的类都可以通过该语句进行自动关闭资源
1.手动关闭资源写法
FileWriter fw=null;
try {
File file=new File(path);
fw=new java.io.FileWriter(file,true);
fw.write(content);
}catch (IOException e){
e.printStackTrace();
}finally {
try {
if (fw!=null){
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
自动关闭资源写法(推荐)
File file=new File(path);
try(FileOutputStream f=new FileOutputStream(file,true);// 构建FileOutputStream对象,文件不存在会自动新建,自动关闭资源
OutputStreamWriter writer=new OutputStreamWriter(f);
) {
writer.append(content);
} catch (IOException e) {
e.printStackTrace();
}