InputStream
, OutputStream
, java.sql.Connection
전통적으로 자원을 닫을 때 try-finally
를 많이 사용했다.
static String firstLineOfFile(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
br.close();
}
}
try
내부와 finally
내부에서 모두 예외가 발생하면 두 번째 발생한 예외가 첫 번째 발생한 예외를 집어삼켜 버린다.또 하나의 단점으로 자원이 추가될 때마다 코드가 지저분해진다.
static void copy(String src, String dst) throws IOException {
InputStream in = new FileInputStream(src)
try {
OutputStream out = new FileOutputStream(dst);
try {
byte[] buf = new Byte[BUFFER_SIZE];
int n;
while ((n == in.read(buf)) >= 0) {
out.write(buf, 0, n);
} finally {
out.close();
}
} finally {
in.close();
}
}
try-with-resources
가 추가되었다.AutoCloseable
인터페이스를 구현해야 한다.
close()
메서드만 구현하면 된다.AutoCloseable
을 구현한 상태다.복수의 자원을 처리하는 try-with-resources
코드
static void copy(String src, String dst) throws IOException {
try (InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dist)) {
byte[] buf = new Byte[BUFFER_SIZE];
int n;
while ((n == in.read(buf)) >= 0) {
out.write(buf, 0, n);
}
}
}