Java 7支持整个目录树的遍历;
Demo:
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;
/**列出子目录下的所有java源码文件
* @author jinxing
* @准备
* /Users/jinxing/Documents/pathtest/path1 log4j.xml、shortUrl.properties、weixinjsapi.properties
* /Users/jinxing/Documents/pathtest/path1/tt ttson.java
*/
public class PathFind {
public static void main(String[] args) throws IOException {
Path startingDir = Paths.get("/Users/jinxing/Documents/pathtest/path1");
// 5.调用walkFileTree:整个过程从此开始;
Files.walkFileTree(startingDir, new FindJavaVisitor());
}
// 其他用例包括递归移动、复制、删除或者修改文件;在大多数应用场景中,你只需要扩展 SimpleFileVisitor;
// 1.扩展 SimpleFileVisitor<Path>
private static class FindJavaVisitor extends SimpleFileVisitor<Path> {
/** 2.唯一要做的就是重写 visitFile,让它来为你工作; **/
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// 3.过滤所有java源码文件
if (file.toString().endsWith(".java")) {
System.out.println(file.getFileName());
}
// 4.return
return FileVisitResult.CONTINUE;
}
}
}
Ran As Java Application:
test.java
test2.java
ttson.java