Recursively list files in Java

后端 未结 27 1594
走了就别回头了
走了就别回头了 2020-11-22 00:29

How do I recursively list all files under a directory in Java? Does the framework provide any utility?

I saw a lot of hacky implementations. But none from the fra

27条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 00:45

    Lists all files with provided extensions,with option to scan subfolders (recursive)

     public static ArrayList listFileTree(File dir,boolean recursive) {
            if (null == dir || !dir.isDirectory()) {
                return new ArrayList<>();
            }
            final Set fileTree = new HashSet();
            FileFilter fileFilter = new FileFilter() {
                private final String[] acceptedExtensions = new String[]{"jpg", "png", "webp", "jpeg"};
    
                @Override
                public boolean accept(File file) {
                    if (file.isDirectory()) {
                        return true;
                    }
                    for (String extension : acceptedExtensions) {
                        if (file.getName().toLowerCase().endsWith(extension)) {
                            return true;
                        }
                    }
                    return false;
                }
            };
            File[] listed = dir.listFiles(fileFilter);
            if(listed!=null){
                for (File entry : listed) {
                    if (entry.isFile()) {
                        fileTree.add(entry);
                    } else if(recursive){
                        fileTree.addAll(listFileTree(entry,true));
                    }
                }
            }
            return new ArrayList<>(fileTree);
        }
    

提交回复
热议问题