Recursively list files in Java

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

    Here a simple but perfectly working solution using recursion:

    public static List listFiles(String rootDirectory)
    {
        List files = new ArrayList<>();
        listFiles(rootDirectory, files);
    
        return files;
    }
    
    private static void listFiles(String path, List collectedFiles)
    {
        File root = new File(path);
        File[] files = root.listFiles();
    
        if (files == null)
        {
            return;
        }
    
        for (File file : files)
        {
            if (file.isDirectory())
            {
                listFiles(file.getAbsolutePath(), collectedFiles);
            } else
            {
                collectedFiles.add(file.toPath());
            }
        }
    }
    

提交回复
热议问题