참고 페이지: (https://www.baeldung.com/java-try-with-resources)
- try 부분에 리소스 선언과 동시에 초기화
try (PrintWriter writer = new PrintWriter(new File("test.txt"))) { writer.println("Hello World"); }
- final로 선언된 리소스 혹은 Effectively Final(명시적 final은 아니지만 참조 변경이 없어 실질적으로 final인) 리소스
final Scanner scanner = new Scanner(new File("testRead.txt")); PrintWriter writer = new PrintWriter(new File("testWrite.txt")) try (scanner;writer) { // omitted }
try ( Scanner scanner = new Scanner(new File("testRead.txt")); PrintWriter writer = new PrintWriter(new File("testWrite.txt")) )세미콜론으로 구별가능
public class MyResource implements AutoCloseable { @Override public void close() throws Exception { System.out.println("Closed MyResource"); } }AutoCloseable 또는 Closeable 인터페이스를 implements 하고
close() 메서드 재정의(@Override)가 필요하다
- 일반적인 try-catch-finally
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 (Scanner scanner = new Scanner(new File("test.txt"))) { while (scanner.hasNext()) { System.out.println(scanner.nextLine()); } } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); }