elevne's Study Note
Java (try-with-resources) 본문
Java 7 에서 새로 추가된 try-with-resources 라는 것에 대해서 알아보았다. 이는 예외 발생 여부와 상관없이 사용했던 리소스 객체 (각종 입출력 스트림, 서버 소켓, 소켓, 각종 채널) 의 close() 메서드를 호출해서 안전하게 리소스를 닫아준다. FileInputStream, FileOutputStream 을 과거 Java 의 try-catch 문 안에서 사용할 때는 아래와 같이 작성해야했다.
public class Main {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("../output.txt");
...
} catch (IOException e) {
...
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {}
}
}
}
}
finally 블록 내에서 다시 try-catch 문을 사용해서 close() 메서드를 예외처리를 진행해주어야 했다. try-with-resources 를 사용하면 아래와 같이 작성하기만 하면 된다.
public class Main {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("../output.txt")){
...
} catch (IOException e) {
...
}
}
}
try 블록이 정상적으로 실행을 완료하거나, 도중에 예외가 발생하게 되면 자동으로 close() 메서드가 호출된다. 여러 개의 리소스를 활용하는 것도 가능하다.
public class Main {
public static void main(String[] args) {
try (
FileInputStream fis = new FileInputStream("../output.txt");
FileOutputStream fos = new FileOutputStream("../output2.txt")
){
...
} catch (IOException e) {
...
}
}
}
try-with-resources 를 사용하기 위해서는 리소스 객체가 java.lang.AutoCloseable 인터페이스를 구현하고 있어야 한다. 아래는 AutoCloseable 을 구현한 예시이다.
package thisisjava;
public class FileInputStream implements AutoCloseable {
private String file;
public FileInputStream(String file){
this.file = file;
}
public void read() {
System.out.println(file + "을 읽습니다.");
}
@Override
public void close() throws Exception {
System.out.println(file + "을 닫습니다.");
}
}
public class Main {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("output.txt")){
fis.read();
throw new Exception();
} catch (Exception e) {
System.out.println("Exception~~");
}
}
}
Reference:
이것이 자바다 (신용권의 Java 프로그래밍 정복)
'Backend > Java' 카테고리의 다른 글
Java 중첩클래스/인터페이스, 익명클래스 (0) | 2023.05.04 |
---|---|
HttpServletRequest, HttpServletResponse (0) | 2023.04.30 |
Java (Singleton, 접근제어, Annotation) (0) | 2023.04.26 |
Java (Primitive Type, Reference Type ~) (0) | 2023.04.25 |
Java Gson (0) | 2023.04.21 |