0%

Try with Resources

Try with Resources语句从JDK1.7引入,让我们可以声明资源Resources在Try代码块中,并且在执行后资源将会关闭。(资源实现AutoCloseable接口)

使用示例

1
2
3
4
5
private static void TryWith() throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
System.out.println(br.readLine());
}
}

在此之前,必须使用finally代码块,确保资源关闭。

1
2
3
4
5
6
7
8
9
10
11
12
13
private static void TryWithout() throws IOException {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("test.txt"));
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
br.close();
}
}
}

多个资源

多个资源可以同时声明在try后面,中间用;分隔。

1
2
3
4
5
6
7
8
9
private static void TryWithMultiple() throws IOException {
try (PrintWriter br = new PrintWriter("test.txt");
Scanner scanner = new Scanner(new File("testRead.txt"))) {
while (scanner.hasNext()) {
br.print(scanner.nextLine());
}
br.flush();
}
}