입출력 스트림, DB 연결 등과 같은 자원을 사용할 때는 기존에 close() 메서드를 호출하여 자원을 해제해주었어야 합니다.
사용 전:
FileInputStream fis = null;
try {
fis = new FileInputStream("file.txt");
// 파일 읽기 작업 수행
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java 7 부터 도입된 `try-with-resources` 문법을 사용하면 코드를 간결하고 효율적으로 작성할 수 있습니다. 기존에는 코드 안에 close() 메서드를 명시하거나 finally 블록을 추가로 작성해야 했습니다. try-with-resources를 사용하면 try 블록이 끝나면 자원을 자동으로 해제해줌으로 번거로움을 줄이고 가독성을 높일 수 있습니다.
사용 후:
try (FileInputStream fis = new FileInputStream("file.txt")) {
// 파일 읽기 작업 수행
} catch (IOException e) {
e.printStackTrace();
}