Java 递归获取路径下所有文件

   /**
     * 递归获取路径下所有文件
     *
     * @param path     要获取的路径
     * @param depth    初始深度
     * @param maxDepth 最大递归深度
     * @return 该路径下所有文件
     */
    private static List<File> rListFiles(File path, int depth, int maxDepth) {
        File[] files = path.listFiles();
        List<File> result = new ArrayList<>();

        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    if (depth < maxDepth) {
                        result.addAll(rListFiles(file, depth + 1, maxDepth));
                    }
                } else {
                    result.add(file);
                }
            }
        }

        return result;
    }

    /**
     * 递归获取路径下所有文件
     *
     * @param path     要获取的路径
     * @param maxDepth 最大深度
     * @return 该路径下所有文件
     */
    private static List<File> rListFiles(File path, int maxDepth) {
        return rListFiles(path, 1, maxDepth);
    }

    /**
     * 递归获取路径下所有文件
     *
     * @param path 要获取的路径
     * @return 该路径下所有文件
     */
    private static List<File> rListFiles(File path) {
        return rListFiles(path, Integer.MAX_VALUE);
    }

    /**
     * 递归获取路径下所有文件
     *
     * @param path 要获取的路径
     * @return 该路径下所有文件
     */
    private static List<File> rListFiles(String path) {
        return rListFiles(new File(path), Integer.MAX_VALUE);
    }

posted @ 2022-01-15 11:23  博麗靈夢  阅读(227)  评论(0编辑  收藏  举报