item 9 dodo4513 - JAVA-JIKIMI/EFFECTIVE-JAVA3 GitHub Wiki
- ์๋ฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์๋ close ๋ฉ์๋๋ฅผ ํธ์ถํด ์ง์ ๋ซ์์ค์ผ ํ๋ ์์์ด ๋ง๋ค. InputStream, OutputStream, java.sql.Connection ๋ฑ์ด ์ข์ ์๋ค. ์์ ๋ซ๊ธฐ๋ ํด๋ผ์ด์ธํธ๊ฐ ๋์น๊ธฐ ์ฌ์์ ์์ธกํ ์ ์๋ ์ฑ๋ฅ ๋ฌธ์ ๋ก ์ด์ด์ง๊ธฐ๋ ํ๋ค.
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-catch ์ง์ฅ์ด ์ด๋ฆฐ๋ค.
- try-finally ๋ ์์์ด 2๊ฐ ์ด์์ธ ๊ฒฝ์ฐ ์์ ํ์๋ฅผ ์ํด 2์ค์ผ๋ก try-catch ๋ฅผ ๊ฐ์ธ์ผ ํ๋ค.
- ์์ชฝ์ finally์์ ์์ธ๊ฐ ๋ฐ์ํ ๊ฒฝ์ฐ ์ต์ด์ ์์ธ๋ ๋ฌด์๋์ด ๋๋ฒ๊น ์ด ํ๋ค์ด์ง๋ค.
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);
}
}
2๊ฐ ์ด์์ ์์๋ ๊น๋ํ๊ฒ ์ฒ๋ฆฌ ๊ฐ๋ฅํ๋ค.
- ์๋ฐ 7์ด ํฌ์ฒํ try-with-resources ๋์ ๋ชจ๋ ํด๊ฒฐ๋์๋ค.
์ด ๊ตฌ์กฐ๋ฅผ ์ฌ์ฉํ๋ ค๋ฉด ํด๋น ์์์ด AutoCloseable ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํ
ํด์ผ ํ๋ค. ๋จ์ํ void๋ฅผ ๋ฐํํ๋ close ๋ฉ์๋ ํ๋๋ง ๋ฉ๊ทธ๋ฌ๋ ์ ์ํ ์ธํฐํ์ด์ค๋ค. ์๋ฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ์๋ํํฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ค์ ์๋ง์ ํด๋์ค์ ์ธํฐํ์ด์ค๊ฐ ์ด๋ฏธ AutoCloseable์ ๊ตฌํํ๊ฑฐ๋ ํ์ฅํด๋๋ค.
๊ผญ ํ์ํด์ผ ํ๋ ์์์ ๋ค๋ฃฐ ๋๋ try-finall ๋ง๊ณ , try-with-resources๋ฅผ ์ฌ์ฉํ์.
์์ธ๋ ์๋ค.
์ฝ๋๋ ๋ ์งง๊ณ ๋ถ๋ช ํด์ง๊ณ , ๋ง๋ค์ด์ง๋ ์์ธ ์ ๋ณด๋ ํจ์ฌ ์ ์ฉํ๋ค.
try-finally๋ก ์์ฑํ๋ฉด ์ค์ฉ์ ์ด์ง ๋ชปํ ๋งํผ ์ฝ๋๊ฐ ์ง์ ๋ถํด์ง๋ ๊ฒฝ์ฐ๋ผ๋, try-with-resources๋ก๋ ์ ํํ๊ณ ์ฝ๊ฒ ์์์ ํ์ํ ์ ์๋ค.