개발/JAVA
Try with resources를 이용한 자원해제 처리
주식쟁이 개발자
2022. 5. 11. 23:40
반응형
기존에 많이 쓰고(보이던) Try catch finally가 아닌
try catch with resources로 자원해제 처리 방법에 대해 정리 해보았습니다
실제 사용
try ( FileOutputStream out = new FileOutputStream(file);){
out.write(content.getBytes(StandardCharsets.UTF_8));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
=> finally와 그 안에 자원해제 처리를 위한 부가 작업 불필요
설명
Try에 자원객체를 전달하면, try 코드블록이 끝남과 동시에 자동으로 자원을 종료해주는 기능 (JDK 7 부터 사용가능)
=> finally, catch 로 각각 종료 처리르 걸지 않아도 된다
=> try()문 안에 복수의 자원을 전달 할 수 있다
단, 이때 try에 전달 가능한 자원은 autoCloseable 인터페이스의 구현체로 한정
장점
Try catch finally 사용시, if, try문을 중복해서 더 사용하는 번거로움(처리를 위한 처리)
= 비즈니스와 무관한 자원해제 처리를 위한 코드를 줄일 수 있다
사용법 (비교)
// 파일 생성 (try-catch-finally)
public void makeFile(String path, String title, String content){
FileOutputStream out = null;
try {
File file = new File(path+"/"+title);
if(!file.exists()) { file.createNewFile(); }
out = new FileOutputStream(file);
out.write(content.getBytes(StandardCharsets.UTF_8));
}catch (Exception e){
e.printStackTrace();
}finally {
if(out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// 파일 생성 (try-catch-with-resource)
public void makeFile2(String path, String title, String content){
File file = new File(path+"/"+title);
try ( FileOutputStream out = new FileOutputStream(file);){
out.write(content.getBytes(StandardCharsets.UTF_8));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
반응형