递归文件夹查找指定文件
-
方式一:java8新增api
public static void findFilesByPath1(Path dirPath) { try { Files.walkFileTree(dirPath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs) { if (filePath.toString().endsWith(".xml")) { System.out.println("find file = " + filePath.getFileName()); return FileVisitResult.CONTINUE; } return FileVisitResult.SKIP_SUBTREE; } //失败,可能是文件没有访问权限等,直接过滤掉 @Override public FileVisitResult visitFileFailed(Path filePath, IOException exception) throws IOException { if (exception instanceof AccessDeniedException) { return FileVisitResult.SKIP_SUBTREE; } return super.visitFileFailed(filePath, exception); } }); } catch (IOException e) { e.printStackTrace(); } }
-
方式二:递归方式
public static void findFilesByPath2(Path path) throws IOException { if (Files.isDirectory(path)) { Files.list(path).forEach(newPath -> { try { findFilesByPath2(newPath); } catch (IOException e) { // e.printStackTrace(); } }); } else { if (path.toString().endsWith(".xml")) { System.out.println("find file = " + path.getFileName()); } } }
调用方式:
findFilesByPath1(Paths.get("E:\\")); findFilesByPath2(Paths.get("E:\\"));