본문 바로가기
JAVA

Try with resources, 자원 자동 해제하기

by 김ㅋㅋㅋ 2022. 7. 1.

Try with resources


java 7에서 추가된 'try with resources'는 try(...) try안에서 선언된 객체들을 try가 끝나면 자동으로 자원해제 해주는  기능입니다.

아래는 텍스트파일에 문자열을 쓰는 간단한 코드입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String[] args) throws IOException {
   BufferedOutputStream bos = null;   
    try {
        bos = new BufferedOutputStream(new FileOutputStream("E:/Test2/TryWithResTest.txt"));
        String str = "Try With Resources Testttttt";
        bos.write(str.getBytes());
    } catch (Exception e) {
        e.getStackTrace();
    } finally {
        if(bos != null)
            bos.close();
    }
}
cs

finally 부분에서 자원 해제를 해주는데 번거로워서 그런지 사람들이 많이 까먹기도 하고 귀찮아하는 코드입니다. 심지어 main의 throws IOException이 없으면 close() 에도 try catch를 써야 합니다.


이러한 번거로움 때문인지 java7에서는 try with resources 기능이 생겼고 그로 인해 코드가 아래처럼 간단해졌습니다.

1
2
3
4
5
6
7
8
public static void main(String[] args) throws IOException {
    try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:/Test2/TryWithResTest.txt"));){
        String str = "Try With Resources Test";
        bos.write(str.getBytes());
    } catch (Exception e) {
        e.getStackTrace();
    }
}
cs

이처럼 try(...) 안에 사용할 자원들을 선언하면 try문이 끝나고 자동으로 자원 해제를 해주는 기능입니다.

 

※ 정확하게는 소괄호 안의 객체 중 AutoCloseable 인터페이스를 상속받아 close()를 구현한 객체들을 자동 해제해주는 기능입니다.
FileOutputStream, BufferedOutputStream등 입출력 스트림들은 클래스에 보면 구현되어있거나 구현한 클래스를 상속받아서 자동 해제됩니다.

 

'JAVA' 카테고리의 다른 글

JAVA IP Address Split(".")  (0) 2021.05.11
[Java 문제] 127 + 1 = ?  (0) 2020.12.29

댓글