Try with resources로 알아서 자원 해제하기
Try-with-resources
// 기존 try-catch-fianlly
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();
}
}
// 자바7부터 try-with-resources
try (Scanner scanner = new Scanner(new File("test.txt"))) { // try문 이후에 알아서 해제된다.
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}AutoCloseable
정리하면
Last updated