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


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

    • 示例代码

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

      在这里插入图片描述

  • 相关阅读:
    Jprofiler的使用查看oom
    Flutter中GetX系列七--依赖注入(put,lazyPut,putAsync)、Binding(统一初始化)
    【无标题】C++库编译
    算法 之 链表
    相机不小心格式化了怎么恢复?如何快速找回珍贵照片
    haproxy,nginx,keepalived综合运用
    Docker安装Mysql
    异步编程-线程实现异步编程
    MATLAB|不给糖果就捣蛋
    .net core 自定义授权策略提供程序进行权限验证
  • 原文地址:https://blog.csdn.net/li1325169021/article/details/126092095