Gangmax Blog

Java: Try with Resources

From here.

Let’s check the following code first:

1
2
3
4
5
6
7
8
9
10
11
12
13
Scanner scanner = null;
try {
scanner = new Scanner(new File("test.txt"));
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}

This is a common case when we’re dealing with some resource need to be closed after using it. If you know “with” in Python, you can see that the code above in Java is more verbose than Python. Fortunately, the “try-with-resources” feature, which was introduced in Java 7, allows us to declare resources to be used in a try block with the assurance that the resources will be closed after the execution of that block. For example:

1
2
3
4
5
6
7
try (Scanner scanner = new Scanner(new File("test.txt"))) {
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Multiple resources are also supported:

1
2
3
4
5
6
7
try (Scanner scanner = new Scanner(new File("testRead.txt"));
PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) {
while (scanner.hasNext()) {
writer.print(scanner.nextLine());
}
}
...

In Python, you need to make the resource object be a “context manager“ object in order to use it in the “with” statement. Correspondingly, in Java you need to make the resource object be an instance which implements the “Closeable“ or “AutoCloseable“ interface and overrides the “close” method, which will be automatically invoked by the “try-with-resources” feature in Java after it’s used.

Comments