Javaの勉強9 NIO.2 Filesやろう!ってWatchableとちょこっとラムダ

昨日の続き。次はFilesについてメモろうと思うんだけど。
その前にPathが実装してるWatchableインターフェイスを見てみよっと。知らないから。

Path - Watchable

Watchable (Java Platform SE 7 )

あ、Path用に1.7で導入されたインターフェイスなのか。
ファイルの変更イベントをWatchできるってことっぽいな。なる。じゃ次いこう。

Files

ファイル処理用のユーティリティクラスすね。

全然関係ないところで

ラムダ式あってしばらく意味を考える。

    /**
     * Convert a Closeable to a Runnable by converting checked IOException
     * to UncheckedIOException
     */
    private static Runnable asUncheckedRunnable(Closeable c) {
        return () -> {
            try {
                c.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        };
    }

まだ頭がついていかないのでゆっくりと。
Runnableが1メソッドだけだからラムダ式にできて。
runしたときにこのcをクローズしてIOEをUncheckedIOEに変換して投げてるってことか。

ふむ。。。何のために?

この2つのStream系のメソッドで使ってるっぽい。なんとなくは分かるけど、ちゃんと理解するのはまだ僕には早いかな。またいつか!

    public static Stream<Path> list(Path dir) throws IOException {
        DirectoryStream<Path> ds = Files.newDirectoryStream(dir);
        try {
            final Iterator<Path> delegate = ds.iterator();

            // Re-wrap DirectoryIteratorException to UncheckedIOException
            Iterator<Path> it = new Iterator<Path>() {
                @Override
                public boolean hasNext() {
                    try {
                        return delegate.hasNext();
                    } catch (DirectoryIteratorException e) {
                        throw new UncheckedIOException(e.getCause());
                    }
                }
                @Override
                public Path next() {
                    try {
                        return delegate.next();
                    } catch (DirectoryIteratorException e) {
                        throw new UncheckedIOException(e.getCause());
                    }
                }
            };

            return StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, Spliterator.DISTINCT), false)
                                .onClose(asUncheckedRunnable(ds));
        } catch (Error|RuntimeException e) {
            try {
                ds.close();
            } catch (IOException ex) {
                try {
                    e.addSuppressed(ex);
                } catch (Throwable ignore) {}
            }
            throw e;
        }
    }

    public static Stream<String> lines(Path path, Charset cs) throws IOException {
        BufferedReader br = Files.newBufferedReader(path, cs);
        try {
            return br.lines().onClose(asUncheckedRunnable(br));
        } catch (Error|RuntimeException e) {
            try {
                br.close();
            } catch (IOException ex) {
                try {
                    e.addSuppressed(ex);
                } catch (Throwable ignore) {}
            }
            throw e;
        }
    }

って、ちょいやりたいことがあるので、一週間くらいJavaの勉強はお休みしよっと。

つか、このコードの例外処理面白いな。