Java 7支持整個目錄樹的遍歷;Demo:import java.io.IOException;import java.nio.file.FileVisitResult;import java.nio.file.Files;import java.nio.file.Path;import java...
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