이펙티브 자바/2장 객체 생성과 파괴

아이템 9 try-finally 보다는 try-with-resources를 사용하라

말랑공룡 2023. 12. 19. 11:21

 

  • 자바 라이브러리에는 close 메서드를 호출해 직접 닫아줘야 하는 자원들이 있다.
  • try-with-resources를 쓰면 AutoCloseable 또는 Closeable 인터페이스를 구현한 자원 객체들을 사용 후, 자동으로 close 하게 할 수 있다.

 

예시

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TryWithResourcesExample {
    public static void main(String[] args) {
        // 파일 경로 지정
        String filePath = "example.txt";

        // try-with-resources를 사용하여 BufferedReader 생성
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            // 파일에서 한 줄씩 읽어오기
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            // IOException 처리
            e.printStackTrace();
        }
        // try-with-resources를 사용하면, 자동으로 close() 메서드가 호출되어 파일 리소스가 닫힘
    }
}