-
[Java7] try-with-resourcesJava/기본 2016. 7. 21. 21:55728x90반응형
스프링부트 책을 보다가 알게된 기능이다.
이런게 있는지 왜 이제야 알게된걸까 ㅋㅋ...
BufferedReader나 JDBC 등을 미리 선언 후
try에서 자원을 할당하고
finally로 null 이 아니면 닫아주는 형식의 코드를 작성하였다.
코드도 길뿐 아니라 깔끔해보이지 않고 무의식적으로 적는 부분이다.
하지만 try-with-resources를 사용하면
try에 바로 자원 할당 후 try가 끝나면 알아서 자원해제.
참고로 catch에 들어가기 전에 이미 다 close를 한다고 한다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characterspublic static void main(String[] args) { BufferedReader br = null; try { String str; br = new BufferedReader(new FileReader("C:\\number.txt")); while ((str = br.readLine()) != null) { System.out.println(str); } } catch (IOException e) { System.out.println(e.getMessage()); } finally { try { if (br != null)br.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characterspublic static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader("C:\\number.txt"))) { String str; while ((str = br.readLine()) != null) { System.out.println(str); } } catch (IOException e) { e.printStackTrace(); } } (출처: http://stackoverflow.com/questions/17650970/am-i-using-the-java-7-try-with-resources-correctly)
반응형'Java > 기본' 카테고리의 다른 글
Reflection 리플렉션 (0) 2018.01.21 [Java9] 자바9 설치 (1) 2017.09.23 [Java7] 자바 숫자 _(언더바) 표현 (2) 2017.07.09 [Java7] readAllLines (0) 2017.02.09 [Java8] String.join (0) 2017.01.21