久しぶりに 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リソースもクローズされます。