자바 라이브러리에는 close 메서드를 호출해 직접 닫아줘야 하는 자원이 많다.

static String firstLineOfFile(final String path) throws IOException {

		final BufferedReader br = new BufferedReader(new FileReader(path));
		try {
				return br.readLine();
		} finally {
				br.close();
		}
}
static void copy(final String src, final String dst) throws IOException {

    final 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-finally 문을 제대로 사용한다고 해도, 미묘한 결점이 있다!

<aside> 💡 이러한 문제들은 자바 7에서 등장한 try-with-resources 로 해결할 수 있다!

</aside>

static String firstLineOfFile(final String path) throws IOException {

		try (final BufferedReader br = new BufferedReader(
						new FileReader(path))) {
				return br.readLine();
		}
}
static void copy(final String src, final String dst) throws IOException {

    try (final 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);
    }
}