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