标签:dir lis port font col import new attribute stat
1.File.walkFileTree():
package com.test; import java.io.File; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.LinkedList; import java.util.List; public class FileFinder { public static void main(String[] args) throws IOException { Path startingDir = Paths.get("D:\\test"); List<String> result = new LinkedList<String>(); Files.walkFileTree(startingDir, new FilterFilesVisitor(result)); System.out.println("result.size()=" + result.size()); for (String name : result) { System.out.println(name); } } private static class FilterFilesVisitor extends SimpleFileVisitor<Path> { private List<String> result = new LinkedList<String>(); public FilterFilesVisitor(List<String> result) { this.result = result; } /** * 正在访问一个文件时要干啥 */ @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { if (file.toString().endsWith(".java")) { result.add(file.toString()); System.out.println("文件名"+file.getFileName()); System.out.println("文件全路径"+file.toString()); File f = file.toFile(); f.delete(); System.out.println(file.getFileName()+"已删除"); } // SKIP_SIBLINGS:继续遍历,但忽略当前节点的所有兄弟节点直接返回上一层继续遍历 // SKIP_SUBTREE:继续遍历,但是忽略子目录,但是子文件还是会访问; // TERMINATE:终止遍历 //继续遍历 return FileVisitResult.SKIP_SUBTREE; } /** * 访问一个目录前要干啥 */ @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { // TODO Auto-generated method stub return super.preVisitDirectory(dir, attrs); } /** * 访问一个目录后要干啥 */ @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { // TODO Auto-generated method stub return super.postVisitDirectory(dir, exc); } /** * 访问一个文件失败时要干啥 */ @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { // TODO Auto-generated method stub return super.visitFileFailed(file, exc); } } }
标签:dir lis port font col import new attribute stat
原文地址:https://www.cnblogs.com/kuangzhisen/p/10158860.html