Java 學習記錄96 — Walk File Tree

import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
public class PrintNames extends SimpleFileVisitor<Path> {
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
System.out.println("Error accessing file: " + file.toAbsolutePath() + " " + exc.getMessage());
return super.visitFileFailed(file, exc);
System.out.println("------ Walking Tree for Dir2 ------");
Path dir2Path = FileSystems.getDefault().getPath(
"src" + File.separator +
"nonBlockingIO" + File.separator +
"path" + File.separator +
"copyExamples" + File.separator +
try {
Files.walkFileTree(dir2Path, new PrintNames());
} catch (IOException e) {
// version 2
Path dir2Path = FileSystems.getDefault().getPath(String.join(File.separator, "src", "nonBlockingIO", "path", "copyExamples", "Dir2"));

上面代碼全都紀錄在我的 Github



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store