zoukankan      html  css  js  c++  java
  • java遍历文件夹及所有子文件

    以前写代码循环文件夹和子文件时,总是自己写递归访问,今天研究lucene时,发现JDK给我们已经提供了访问遍历的方法,上代码:

     1 String str = "C:\Users\LLY\Desktop\新建文件夹";
     2         Path path = Files.walkFileTree(Paths.get(str), new SimpleFileVisitor<Path>(){
     3 
     4             /**
     5              * 访问文件夹前执行
     6              * @param dir
     7              * @param attrs
     8              * @return
     9              * @throws IOException
    10              */
    11             @Override
    12             public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
    13                 return super.preVisitDirectory(dir, attrs);
    14             }
    15 
    16             /**
    17              * 访问文件
    18              * @param file
    19              * @param attrs
    20              * @return
    21              * @throws IOException
    22              */
    23             @Override
    24             public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    25                 return super.visitFile(file, attrs);
    26             }
    27 
    28             /**
    29              * 访问失败执行
    30              * @param file
    31              * @param exc
    32              * @return
    33              * @throws IOException
    34              */
    35             @Override
    36             public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
    37                 return super.visitFileFailed(file, exc);
    38             }
    39 
    40             /**
    41              * 文件夹所有文件刚问完后执行
    42              * @param dir
    43              * @param exc
    44              * @return
    45              * @throws IOException
    46              */
    47             @Override
    48             public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
    49                 return super.postVisitDirectory(dir, exc);
    50             }
    51         });
  • 相关阅读:
    Django入门
    Python从入门到放弃
    Python中的元类(metaclass)
    蓝鲸gse启动失败
    VS2019添加微软ReportViewer
    DevExpress WinForms各版本与 .NET、Visual Studio 的版本兼容性
    SQL语句查询每个分组的前N条记录的实现方法
    如何查看Windows安装版本号
    学习webpack
    Python3.x将代码打包成exe程序并添加图标
  • 原文地址:https://www.cnblogs.com/lly001/p/10958695.html
Copyright © 2011-2022 走看看