使用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成员字符串里的内容,并不会深入文件系统用完整的绝对路径来比较

原文地址:https://www.cnblogs.com/cq-yangzhou/p/10697550.html