Java 學習記錄96 — Walk File Tree

import java.io.IOException;
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> {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
System.out.println(file.toAbsolutePath());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
System.out.println(dir.toAbsolutePath());
return FileVisitResult.CONTINUE;
}
@Override
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 +
"Dir2");
try {
Files.walkFileTree(dir2Path, new PrintNames());
} catch (IOException e) {
System.out.println(e.getMessage());
}
// 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
張小雄

張小雄

記錄成為軟體工程師的過程