使用try-catch-finally关闭资源情况

//读取⽂本⽂件的内容
Scanner scanner = null;
try {
scanner = new Scanner(new File("D://read.txt"));
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
if (scanner != null) {
scanner.close();
}
}

使用try-with-resources关闭资源情况

声明单个资源要关闭的情况:


try ( Scanner scanner = new Scanner(new File("test.txt")) ) {
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

声明多个资源要关闭情况:

try (
BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("test.txt")));
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")))
) {
int b;
while ((b = bin.read()) != -1) {
bout.write(b);
}
}
catch (IOException e) {
e.printStackTrace();
}