问题
在Java中如果打开了外部资源,用完后必须手动关闭,为了确保外部资源一定要被关闭,通常关闭代码被写入finally代码块中
作用
在Java编程过程中,如果打开了外部资源(文件、数据库连接、网络连接等),我们必须在这些外部资源使用完毕后,手动关闭它们
因为外部资源不由JVM管理,无法享用JVM的垃圾回收机制,如果我们不在编程时确保在正确的时机关闭外部资源,就会导致外部资源泄露,紧接着就会出现文件被异常占用,数据库连接过多导致连接池溢出等诸多很严重的问题
为了确保外部资源一定要被关闭,通常关闭代码被写入finally代码块中,当然我们还必须注意到关闭资源时可能抛出的异常
普通资源释放方法
/**
* 普通的资源释放方法
*/
@Test
public void testDemo2() {
Scanner scanner = null;
try {
scanner = new Scanner(new File("xxx")); //这里的路径一定要写完整路径
while (scanner.hasNext()) {
System.out.println(scanner.nextLine()); //逐行读取
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
//读取完毕则关闭
if (scanner != null) {
scanner.close();
}
}
}
try-with-resource
try-with-resource是Java7新增的语法,会自动关闭资源
/**
* 使用try-with-resource方法会自动关闭资源
*/
@Test
public void testDemo3() {
try (Scanner scanner = new Scanner(new File("xxx"))) {
while (scanner.hasNext()) {
//逐行读取文件中的内容
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException file) {
file.printStackTrace();
}
}
关闭多个资源的情况:
/**
* 使用try-with-resource关闭多个资源
*/
@Test
public void testDemo4() {
try (Scanner scanner = new Scanner(new File("xxx"));
PrintWriter writer = new PrintWriter(new File("xxx"))
) {
while (scanner.hasNext()) {
//test.txt文件的内容写入到test2中
writer.println(scanner.nextLine());
}
} catch (FileNotFoundException file) {
file.printStackTrace();
}
}