Java 에서 자원 할당하고 해제하기 (괜찮은 패턴)
Java 에서 자원을 할당하고 해제하는 코드는 상당히 귀찮고 코드도 복잡하게 될 수 있다.
보통 아래와 같이 코드를 작성한다.
public void test(String inputFileName, String outputFileName) { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(inputFileName); out = new FileOutputStream(outputFileName); copy(in, out); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } |
하지만 아래와 같이 작성하면, 자원을 할당하고 해제하는 코드를 깔끔하게 작성할 수 있다.
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(inputFileName);
out = new FileOutputStream(outputFileName);
copy(in, out);
finally {
close(in);
close(out);
}
public static void close(Closeable c) {
if (c == null) return;
try {
c.close();
} catch (IOException e) {
//log the exception
}
}
출처: http://stackoverflow.com/questions/2699209/java-io-ugly-try-finally-block/2699270#2699270