close메서드를 이용한 자원 회수는 놓치기가 쉽다.
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 { //자원 두개를 회수하기 위해서 finally 두번 처리
in.close();
}
}
static String firstLineOfFile(String path, String defaultVal) {
try (BufferedReader br = new BufferedReader(
new FileReader(path))) {
return br.readLine();
} catch (IOException e) {
return defaultVal;
}
}
- 꼭 회수해야 하는 자원을 다룰 때는 try-finally 대신 try-with-resources를 사용