Java IO & NIO - Files.walk() Examples

Code Snippets Java IO & NIO Java 


Class:

java.nio.file.Files

java.lang.Objectjava.lang.Objectjava.nio.file.Filesjava.nio.file.FilesLogicBig

Methods:

public static Stream<Path> walk(Path start,
                                FileVisitOption... options)
                         throws IOException
public static Stream<Path> walk(Path start,
                                int maxDepth,
                                FileVisitOption... options)
                         throws IOException

Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.

Parameters:
start - the starting file
maxDepth - the maximum number of directory levels to visit
options - options to configure the traversal
Returns:
the java.util.stream.Stream,Stream of java.nio.file.Path



Examples


package com.logicbig.example.files;

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.Stream;

public class WalkExample {

public static void main(String... args) throws IOException {
Path start = Paths.get("C:\\temp");
Stream<Path> stream = Files.walk(start, 3, FileVisitOption.FOLLOW_LINKS);
stream.limit(10)
.forEach(System.out::println);
}
}

Output

C:\temp
C:\temp\copy-file-test.txt
C:\temp\my-file12337966864934082418.txt
C:\temp\my-shared-file.txt
C:\temp\settings
C:\temp\settings\settings.xml
C:\temp\settings\sub-settings
C:\temp\settings\sub-settings\settings.xml
C:\temp\test-file3025046793500652276.txt
C:\temp\test.txt




See Also