• 使用nio遍历文件夹


    1、递归方式:

    private static void print(File f){
            if(f!=null){
                if(f.isDirectory()){
                    File[] fileArray=f.listFiles();
                    if(fileArray!=null){
                        for (int i = 0; i < fileArray.length; i++) {
                            //递归调用
                            print(fileArray[i]);
                        }
                    }
                }
                else{
                    System.out.println("文件为:"+f.getName())
                }
            }
        }

    2、nio方式

    /**
         * nio遍历文件夹下面所有的文件
         * @return
         * @throws IOException
         */
        private static List<File> getFiles(String path) throws IOException {
            List<File>files = new ArrayList<>();
            Files.walkFileTree( Paths.get(path),new SimpleFileVisitor<Path>(){
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
    //                System.out.println("正在访问:" + dir + "目录");
                    return FileVisitResult.CONTINUE;
                }
    
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    //                System.out.println("	正在访问" + file + "文件");
                    files.add(file.toFile());
                    return super.visitFile(file, attrs);
                }
    
            });
            return  files;
        }

    !!注意,里面的文件和目录要区别开;

    !可以看到它是一个模板接口,但是在walkFileTree中它的类型已经确定了就是Path,因此里面的T类型就是Path类型了;

            iv. 接口方法的返回值FileVisitResult是一个枚举类型,walkFileTree就是会根据这个返回值决定是否要继续遍历下去,如果要继续遍历则应该怎样遍历,它总共有4个枚举值:都是FileVisitResult中定义的枚举值

    CONTINUE:继续遍历

    SKIP_SIBLINGS:继续遍历,但忽略当前节点的所有兄弟节点直接返回上一层继续遍历

    SKIP_SUBTREE:继续遍历,但是忽略子目录,但是子文件还是会访问;

    TERMINATE:终止遍历

    实际使用中通常直接继承FileVisitor的适配器SimpleFileVisitor,因为只需要实现你感兴趣的方法即可,无需4个方法全部都实现;

    !!Path可以像String那样进行字符串校验,校验路径中的字符串:都是Path的对象方法

            a. boolean startsWith(String other); // 前缀检查

            b. boolean startsWith(Path other);

            c. boolean endsWith(String other); // 后缀检查

            d. boolean endsWith(Path other);

    !!比较的都是其path成员字符串里的内容,并不会深入文件系统用完整的绝对路径来比较

  • 相关阅读:
    知识点复习
    【程序人生】一个IT人的立功,立言,立德三不朽
    【朝花夕拾】Android多线程之(三)runOnUiThread篇——程序猿们的贴心小棉袄
    【朝花夕拾】Android多线程之(二)ThreadLocal篇
    【朝花夕拾】Android多线程之(一)View.post()篇
    Camera2笔记
    HangFire多集群切换及DashBoard登录验证
    Linq 动态多条件group by
    Api接口签名验证
    postgre ||连接字段
  • 原文地址:https://www.cnblogs.com/cq-yangzhou/p/10697550.html
Copyright © 2020-2023  润新知