기본 콘텐츠로 건너뛰기

2월, 2020의 게시물 표시

(java) try-with-resources

https://www.baeldung.com/java-try-with-resources try 구문절에 resources 사용구문을 입력할 수 있다. 1 2 3 try (PrintWriter writer = new PrintWriter( new File( "test.txt" ))) {      writer.println( "Hello World" ); } 구문절에 기존에 try-catch-finally를 사용할때는 보통 아래처럼 한다. try에서 열어주고, finally에서 닫아주고  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();      } } 이걸 다시 try-with-resources 방식으로 하면 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