覚えたら書く

IT関係のデベロッパとして日々覚えたことを書き残したいです。twitter: @yyoshikaw

Files.lines(Path) 利用時は try-with-resources とともに利用する

久しぶりに Java 触ったときに何の悪気もなく以下のようなコードを書いてしまいました。

public class FilesTrial {

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("/home/hogehoge/dummy.txt");

        Files.lines(path).forEach(line -> {
            String upperStr = line.toUpperCase(Locale.JAPAN);
            System.out.println(upperStr);
        });
}

実はこのコードだとStreamの元となっているIOリソースがクローズされません。
そのため、こういうコード書いちゃだめです。

忘れてました。。。


Files.lines(Path) を使うときは、try-with-resources で囲むという方法をとるのがよいです。

public class FilesTrial {

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("/home/hogehoge/dummy.txt");

        // try-with-resources を使うのが正しい
        try (Stream<String> stream = Files.lines(path)) {
            stream.forEach(line -> {
                String upperStr = line.toUpperCase(Locale.JAPAN);
                System.out.println(upperStr);
            });
        }

    }
}

これにより Streamの元となっているIOリソースもクローズされます。



関連ページ