Netty——Files类的walkFileTree方法遍历文件夹和文件夹下的文件

x33g5p2x  于2022-08-17 转载在 其他  
字(1.2k)|赞(0)|评价(0)|浏览(608)

一、walkFileTree方法遍历文件夹和文件夹下的文件

  • 示例代码
  1. package com.example.nettytest.nio.day2;
  2. import java.io.IOException;
  3. import java.nio.file.*;
  4. import java.nio.file.attribute.BasicFileAttributes;
  5. import java.util.concurrent.atomic.AtomicInteger;
  6. /**
  7. * @description:
  8. * @author: xz
  9. * @create: 2022-07-31 10:31
  10. */
  11. public class TestWalkFileTree {
  12. public static void main(String[] args) throws IOException {
  13. foreachDirectory();
  14. }
  15. /**
  16. *遍历件夹和文件夹下的文件
  17. * */
  18. private static void foreachDirectory() throws IOException {
  19. //计数器:文件夹数量
  20. AtomicInteger dirCount = new AtomicInteger();
  21. //计数器:文件数量
  22. AtomicInteger fileCount = new AtomicInteger();
  23. //walkFileTree遍历文件树
  24. Files.walkFileTree(Paths.get("D:\\Java\\jdk1.8.0_161"),new SimpleFileVisitor<Path>(){
  25. //重写进入文件夹之前方法
  26. @Override
  27. public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
  28. System.out.println("进入文件夹===>"+dir);
  29. dirCount.incrementAndGet();
  30. return super.preVisitDirectory(dir, attrs);
  31. }
  32. //重写遍历文件方法
  33. @Override
  34. public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
  35. System.out.println("文件路径===>"+file);
  36. fileCount.incrementAndGet();
  37. return super.visitFile(file, attrs);
  38. }
  39. });
  40. System.out.println("文件夹数量:" +dirCount);
  41. System.out.println("文件数量:" +fileCount);
  42. }
  43. }
  • 输出结果如下:

相关文章