1、平常关闭文件流的代码如下
public static void main(String[] args) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("temp.txt"));
System.out.println("流操作");
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我们会在finally中,首先判断fos是否为空,然后进行关闭
2、使用try()操作流
private static void closeStream() throws IOException {
try(FileOutputStream fos = new FileOutputStream(new File("temp.txt"))){
System.out.println("流操作");
}
}
上面2段代码的作用是一样的,try(){},括号里面的对象只要实现接口AutoCloseable,都会执行里面的close()方法。上面的FileOutputStream中close方法其实就是实现AutoCloseable中的close()方法