백엔드/java
[java/자바] try-with-resource 구문 / 자원 자동 반납
첸첸
2023. 8. 3. 20:16
728x90
구글 stt 연동 예제를 살펴보다 try-with-resource 구문을 사용한 곳이 있어, try-with-resource에 대해서 공부하게 되었다.
잘 알고 있는 try-catch-finally 구문의 경우에는 아래의 예시 처럼 finally에서 사용한 자원을 직접 close를 시켜주어야한다.
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();
}
}
그러나 try-with-resource를 사용하는 경우 try 구문이 끝난 다음 사용한 객체를 자동으로 close를 시켜준다.
[사용방법]
try () 안에 에러가 발생할 수 있는 부분을 적어준다.
//한가지의 경우
try (Scanner scanner = new Scanner(new File("test.txt"))) {
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
//여러개의 경우
try (Scanner scanner = new Scanner(new File("test.txt"));
PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) {
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
그럼 모든 객체를 다 자동으로 close를 시켜줄까? 🤔
정답은 아니다.
try에서 사용한 객체가 자동으로 close가 되려면 해당 객체를 만든 class가 Closeable 혹은 AutoCloseable 인터페이스를 구현해야하고 close 메소드를 override 해야한다. 위 예제에서 사용한 Scanner class를 보면 정말로 Closeable 인터페이스를 구현 한 걸 확인 해 볼 수 있다.