본문 바로가기
Programing/JAVA & JSP

[Java] try with resources

by 미미믹 2021. 2. 5.

Java 7에 추가된 try with resources
기존 try catch finally문의 close를 자동으로 close 해준다

기존 try ~ catch ~ finally

FileInputStream fis = null;
BufferedInputStream bis = null;

try {
	fis = new FileInputStream("");
	bis = new BufferedInputStream(fis);
} catch(IOException e) {
	e.printStackTrace();
} finally {
	// close 처리
	if (fis != null) {
		try {
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	if (bis != null) {
		try {
			bis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

try ~ with ~ resources

try (
	FileInputStream fis = new FileInputStream("");
	BufferedInputStream bis = new BufferedInputStream(fis);
) {
} catch (IOException e) {
	e.printStackTrace();
}

try ~ with ~ resources 사용 조건
 - 해당 객체가 AutoCloseable을 구현(implemetns)한 객체일 경우만 자동 close()가 실행된다
 - BufferedInputStream, FileInputStream의 경우 상속받은 java.io.InputStream 클래스에 AutoCloseable을 상속받은 Closeable이 구현되어 있다
 - 직접 만든 클래스일 경우 해당 구문 사용을 위해선 implements AutoCloseable 또는 implemetns Closeable 구문을 추가해야한다

public interface Closeable extends AutoCloseable {
	...
}

public abstract class InputStream implements Closeable {
	...
}

public class FileInputStream extends InputStream {
	...
}

public class BufferedInputStream extends FilterInputStream {
	...
}

try ~ with ~ resources 관련 Java Document

 

The try-with-resources Statement (The Java™ Tutorials > Essential Classes > Exceptions)

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated

docs.oracle.com

중첩 try with resources 는 어떻게 작동할까?

 

중첩 try with resources 는 어떻게 작동할까?

자바를 이용해 외부 자원에 접근하는 경우 한가지 주의해야할 점은 외부자원을 사용한 뒤 제대로 자원을 닫아줘야한다는 점이다. public static void main(String[] args) { FileInputStream fis = null; try{ fis..

multifrontgarden.tistory.com

 

728x90

'Programing > JAVA & JSP' 카테고리의 다른 글

[JAVA] jdk 21 설치 및 환경변수 설정  (0) 2024.02.14
[Java] Arrays 클래스 (java.util.Arrays)  (1) 2021.02.05