Try With Resources
Resources such as files, sockets, and scanners need to be closed. A try-with-resources statement closes each declared resource automatically.
Automatic closing works even when the body throws, and it preserves failures more carefully than hand-written cleanup code.
Close a resource automatically
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try (Scanner input = new Scanner("status")) {
String command = input.nextLine();
System.out.println("Read: " + command);
}
}
}
Output:
Read: status
The Scanner is available inside the try block and is closed when control leaves that block.
A resource must implement AutoCloseable. Declare resources in acquisition order; Java closes them in reverse order.
Put Scanner in the try-with-resources header and read one person's name.