자바 라이브러리에는
close()
를 호출해 직접 닫아줘야 하는 자원이 많다.e.g. InputStream, OutputStream, Connection 등
자원 닫기를 제대로 보장하는 수단으로
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();
}
}
}
try-with-reousrces
등장이러한 문제를 해결하기 위해 Java7 에서
try-with-resources
가 등장했다.
close()
하나만 정의한 인터페이스임static void copy(String src, String dst) throws IOException {
try (InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst)) {
byte[] buf = new byte[BUFFER_SIZE];
int n;
while ((n = in.read(buf)) >= 0) {
out.write(buf, 0, n);
}
}
}
try-with-resources
장점