Bibi's DevLog ๐ค๐
[Java] try-with-resources ๊ฐ๋ ๊ณผ ์ฌ์ฉ๋ฒ ๋ณธ๋ฌธ
๐ฅ BE ๋ฐฑ์๋/Java ์๋ฐ
[Java] try-with-resources ๊ฐ๋ ๊ณผ ์ฌ์ฉ๋ฒ
๋น๋น bibi 2021. 2. 22. 22:53์๋ฐ try-with-resources
์ฐธ๊ณ :
๐badldung, stackoverflow, ๊ตฌ๊ธ๋ง1, ๊ตฌ๊ธ๋ง2
๊ฐ์ฌํฉ๋๋ค๐โโ๏ธ
try-with-resources
๋?
: try()
์ ์์ ๊ฐ์ฒด๋ฅผ ์ ์ธํด ์ฌ์ฉํ๋ฉด, try ๋ธ๋ก์ด ๋๋ ๋ ํด๋น ์์์ ์๋์ผ๋ก ์ข
๋ฃ(close()
)ํด ์ค๋ค.
๋จ, ์ ์ธ๋ ์์์ AutoCloseable
์ธํฐํ์ด์ค๊ฐ ๊ตฌํ๋ ๊ฐ์ฒด์ฌ์ผ ํ๋ค.
try-with-resources
์ฌ์ฉํ๊ธฐ
try ()
์๊ดํธ ๋ด์ ์ฌ์ฉํ ์์์ ์ ์ธํ๋ค.AutoCloseable
์ธํฐํ์ด์ค๊ฐ ๊ตฌํ๋์ด ์์ด์ผ ํ๋ค.
try (PrintWriter writer = new PrintWriter(new File("test.txt"))) {
writer.println("Hello World");
}
- ์ฌ์ฉ์ ์ง์ ์์์ ์ ์ธ ๋ฐ ์ฌ์ฉํ๋ ค๋ฉด
AutoClosable
๋๋Closable
์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํ๊ณ ,close()
๋ฉ์๋๋ฅผ ์ฌ์ ์ํด์ผ ํ๋ค.
public class MyResource implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("Closed MyResource");
}
}
- ์ฌ๋ฌ ์์์ ์ธ๋ฏธ์ฝ๋ก (
;
)์ผ๋ก ๊ตฌ๋ถํด ์ ์ธ ๋ฐ ์ฌ์ฉํ ์ ์๋ค.
try (Scanner scanner = new Scanner(new File("testRead.txt"));
PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) {
while (scanner.hasNext()) {
writer.print(scanner.nextLine());
}
}
(์ฅ์ ) ๊ธฐ์กด์ try-catch-finally ์ฝ๋๋ฅผ ๊ฐ๊ฒฐํ๊ฒ ๋ง๋ค ์ ์๋ค.
- try-catch-finally ์ฝ๋
Scanner scanner = null; try { scanner = new Scanner(new File("test.txt")); while (scanner.hasNext()) { System.out.println(scanner.nextLine()); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (scanner != null) { scanner.close(); } }
try-with-resource
์ฝ๋
try (Scanner scanner = new Scanner(new File("test.txt"))) { while (scanner.hasNext()) { System.out.println(scanner.nextLine()); } } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); }
'๐ฅ BE ๋ฐฑ์๋ > Java ์๋ฐ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Java] ๋๋ค์, ํจ์ํ ์ธํฐํ์ด์ค (0) | 2021.02.23 |
---|---|
[Java] StringBuffer, StringBuilder ๊ทธ๋ฆฌ๊ณ String / StringBuffer ๊ฐ๋ ๊ณผ ์ฌ์ฉ / Buffer์ ๊ฐ๋ (0) | 2021.02.22 |
[Java] Value Object (VO) ๊ฐ ๊ฐ์ฒด (0) | 2021.02.18 |
[Java] enum (์ด๊ฑฐํ) (0) | 2021.02.18 |
[Java] final (ํด๋์ค, ๋ฉ์๋, ๋ณ์, ์ธ์คํด์ค๋ณ์) (0) | 2021.02.18 |