Site Search:

Use Stream API with NIO.2

Back>

Several Files method returns a stream, which allow us to traversal directories and dump file contents.
Files and Path
Files and Path

  • public static Stream<Path> walk(Path start, int maxDepth, FileVisitOption... options) throws IOException
  • public static Stream<Path> find(Path start, int maxDepth, BiPredicate<Path, BasicFileAttributes> matcher, FileVisitOption... options) throws IOException
  • public static Stream<Path> list(Path dir) throws IOException
  • public static Stream<String> lines(Path path) throws IOException

The walk method use depth first search to traversal file system start from start path. By default the maxDepth is Integer.MAX_VALUE. The FileVisitOption has only one constant which is FOLLOW_LINKS option. The walk's default behavior is not FOLLOW_LINKS. When FOLLOW_LINKS is specified, walking may go in an infinite loop due to cycle paths. In that case, FileSystemLoopException will be thrown if cycle is detected.

Notice these static methods all throws IOException, list(Path dir) is equivalent to walk(Path start, int maxDepth) with maxDepth set to 1.

The Files.lines(path) method is equivalent to Files.getAllLines(path).stream(), except Files.lines(path) don't load the whole lines into memory as Files.getAllLines(path) has to do.

OCPJP>cat NIOStreamTest.java 
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
public class NIOStreamTest {
    public static void main(String... args) {
        try {
            Files.walk(Paths.get(".")).filter(p -> p.endsWith("NIOStreamTest.java")).forEach(System.out::println);
            
            Files.list(Paths.get(".")).filter(p -> p.endsWith("NIOStreamTest.java"))
                    .forEach(System.out::println);
            
            Path me = Files.find(Paths.get("."), 10, 
                    (p, a) -> p.endsWith("NIOStreamTest.java") && a.isRegularFile(), FileVisitOption.FOLLOW_LINKS)
                    .findAny().get();
            Long count = Files.lines(me).collect(Collectors.counting());
            System.out.println(count);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
OCPJP>
OCPJP>
OCPJP>javac NIOStreamTest.java 
OCPJP>java NIOStreamTest
./NIOStreamTest.java
./NIOStreamTest.java
24
OCPJP>