转自:https://blog.csdn.net/cyan20115/article/details/106548324
Java 8中提供了Files.walk
API
1.列出所有文件。
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) { List<String> result = walk.filter(Files::isRegularFile).map(x -> x.toString()).collect(Collectors.toList()); result.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); }
2.列出所有文件夹。
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) { List<String> result = walk.filter(Files::isDirectory).map(x -> x.toString()).collect(Collectors.toList()); result.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); }
3.列出所有以.txt
结尾的文件
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) { List<String> result = walk.map(x -> x.toString()).filter(f -> f.endsWith(".txt")).collect(Collectors.toList()); result.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); }
4.获得所有文件
List<File> filesInFolder= new ArrayList<>(); try (Stream<Path> walk = Files.walk(Paths.get(fileCatalogue))){ filesInFolder= walk.filter(Files::isRegularFile).map(Path::toFile).collect(Collectors.toList()); }catch (IOException e){ e.printStackTrace(); }
标签:Files,Paths,Java,示例,walk,filter,printStackTrace,result From: https://www.cnblogs.com/person008/p/16742493.html