Search

IO/NIO API additions - java 8 features

Most of these additions give you ways to obtain java.util.stream.Stream from files and InputStreams. They're a bit different from the streams you obtain from regular collections though. For one, they may throw UncheckedIOException. Also, they are instances of streams where using the stream.close() method is necessary. Streams implement AutoCloseable and can therefore be used in try-with-resources statements. Streams also have an onClose(Runnable) intermediate operation that I didn't list in the earlier section about streams. It allows you to attach handlers to a stream that execute when it is closed. Here is an example:
// Print the lines in a file, then "done"
try (Stream lines = Files.lines(path, UTF_8)) {
    lines.onClose(() -> System.out.println("done"))
              .forEach(System.out::println);
}


1 comment: