Java IO & NIO - Files.walkFileTree() 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 Path walkFileTree(Path start,
                                FileVisitor<? super Path> visitor)
                         throws IOException
public static Path walkFileTree(Path start,
                                Set<FileVisitOption> options,
                                int maxDepth,
                                FileVisitor<? super Path> visitor)
                         throws IOException

Walks a file tree.

Parameters:
start - the starting file
options - options to configure the traversal
maxDepth - the maximum number of directory levels to visit
visitor - the file visitor to invoke for each file
Returns:
the starting file



Examples


package com.logicbig.example.files;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashSet;

public class WalkFileTreeExample {


public static void main(String... args) throws IOException {
String pathString = "C:\\temp";
Files.walkFileTree(Paths.get(pathString),new HashSet<>(), 2, new FileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
System.out.println("preVisitDirectory: " + dir);
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
System.out.println("visitFile: " + file);
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult visitFileFailed(Path file, IOException exc)
throws IOException {
System.out.println("visitFileFailed: " + file);
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
System.out.println("postVisitDirectory: " + dir);
return FileVisitResult.CONTINUE;
}
});


}
}

Output

preVisitDirectory: C:\temp
visitFile: C:\temp\copy-file-test.txt
visitFile: C:\temp\my-file12337966864934082418.txt
visitFile: C:\temp\my-shared-file.txt
preVisitDirectory: C:\temp\settings
visitFile: C:\temp\settings\settings.xml
visitFile: C:\temp\settings\sub-settings
postVisitDirectory: C:\temp\settings
visitFile: C:\temp\test-file3025046793500652276.txt
visitFile: C:\temp\test.txt
visitFile: C:\temp\test10.txt
visitFile: C:\temp\test3.txt
visitFile: C:\temp\test5.txt
visitFile: C:\temp\trish-file.txt
postVisitDirectory: C:\temp




See Also