• File类中的listFile方法还可使用文件过滤器


    #### 综合案例

    #### 文件搜索

    搜索:D:DeveloprHoll目录中的所有.txt文件

    ```java
    public static void getAllTxt(File dir){
    File[] files = dir.listFiles();
    //遍历
    for (File file : files) {
    if(file.isDirectory()){
    getAllTxt(file);
    }else{
    //获取文件的名称 链式编程
    if(file.getName().toLowerCase().endsWith(".txt")){
    System.out.println(file);
    }
    }

    }

    ```

    #### 文件过滤器优化

    java.io.FileFilter 是一个接口,是一个File的过滤器,改接口的对象可以传递给File类的list的listFiles(File Filter)作为参数,接口当中只有一个方法:

    boolean accept(File pathname):测试pathname是否应该包含在当前的file目录中:如果符合返回true,

    实现或者使用匿名内部类重写FileFilter,重定义accept方法的过滤规则

    ```java
    public class Demo06Recursion implements FileFilter {
    public boolean accept(File pathname) {
    if (pathname.isDirectory()){
    return true;
    }
    return pathname.getName().toLowerCase().endsWith(".txt");//所有的都不满足
    }
    }
    ||
    new FileFilter(){
    @Override
    public boolean accept(File pathname) {
    if (pathname.isDirectory()){
    return true;
    }
    return pathname.getName().toLowerCase().endsWith(".txt");//所有的都不满足
    }
    }
    ```

    然后我们我们来使用该过滤器,

    1.先获取一个目录

    2.使用该目录来调用过滤器

    ```java
    File file = new File("D:\Developr\Holl")//使用File类来映射了一个文件
    File[] files = dir.listFiles(new Demo06Recursion());//对该文件如果有子目录就把他的子目录放入一个File数组,再哟弄这个数组调用上面重写的过滤器
    for (File file : files) {//遍历
    if(file.isDirectory()){//如果文件的子文件还是目录就递归重新再判断并过来输出
    getAllTxt(file);
    }else{//如果是文件就直接输出
    System.out.println(file.getName());
    }
    }

  • 相关阅读:
    第一次会议(2019.3.4)
    改革春风吹满地小组~~成立了~~⭐😄~~
    PYQT5 系列(一)——参考自《弗兰克万岁》
    Springboot2.0学习笔记1__微服务及springboot的作用
    Java学习之---------------反射
    Jquery对select的操作 添加一个select
    匿名函数
    数据库迁移
    EF 未应用自动迁移,因为自动迁移会导致数据丢失的解决办法
    在Chrome+Visual Studio中调试asp.net程序很慢的问题(Firefox也有类似问题)
  • 原文地址:https://www.cnblogs.com/rosiness/p/14152584.html
Copyright © 2020-2023  润新知