https://www.baeldung.com/java-try-with-resources
try 구문절에 resources 사용구문을 입력할 수 있다.
이걸 다시 try-with-resources 방식으로 하면
여기서 다른점은 scanner.close() 가 없다.
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(); }
}
|
|
알아서 자원을 반납을 해준다.
java7 부터 사용가능하다.
AutoCloseable 이라는 인터페이스를 사용해서 커스마이징 하는는 방법도 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| public class AutoCloseableResourcesFirst implements AutoCloseable { public AutoCloseableResourcesFirst() { System.out.println("Constructor -> AutoCloseableResources_First"); } public void doSomething() { System.out.println("Something -> AutoCloseableResources_First"); } @Override public void close() throws Exception { System.out.println("Closed AutoCloseableResources_First"); }} |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| public class AutoCloseableResourcesSecond implements AutoCloseable { public AutoCloseableResourcesSecond() { System.out.println("Constructor -> AutoCloseableResources_Second"); } public void doSomething() { System.out.println("Something -> AutoCloseableResources_Second"); } @Override public void close() throws Exception { System.out.println("Closed AutoCloseableResources_Second"); }} |
private void orderOfClosingResources() throws Exception { try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst(); AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) { af.doSomething(); as.doSomething(); }}
Constructor -> AutoCloseableResources_First
Constructor -> AutoCloseableResources_Second
Something -> AutoCloseableResources_First
Something -> AutoCloseableResources_Second
Closed AutoCloseableResources_Second
Closed AutoCloseableResources_First
댓글
댓글 쓰기