Recursively list files in Java

后端 未结 27 1636
走了就别回头了
走了就别回头了 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:56

    No external libraries needed.
    Returns a Collection so you can do whatever you want with it after the call.

    public static Collection listFileTree(File dir) {
        Set fileTree = new HashSet();
        if(dir==null||dir.listFiles()==null){
            return fileTree;
        }
        for (File entry : dir.listFiles()) {
            if (entry.isFile()) fileTree.add(entry);
            else fileTree.addAll(listFileTree(entry));
        }
        return fileTree;
    }
    

提交回复
热议问题