java 在文件夹以及子文件夹中遍历获取指定文件的list

1.  使用java 递归方法获取指定文件的list,相当于在一个文件夹以及子文件夹,搜索文件的功能。

直接上代码: 

 public static List searchFiles(String folderPath, String fileName) {
        List fileList = new ArrayList<>();
        File folder = new File(folderPath);
        if (folder.exists()) {
            searchFilesRecursive(folder, fileName, fileList);
        }
        return fileList;
    }

    private static void searchFilesRecursive(File folder, String fileName, List fileList) {
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    searchFilesRecursive(file, fileName, fileList);
                } else if (file.getName().equals(fileName)) {
                    fileList.add(file);
                }
            }
        }
    }

    public static void main(String[] args) {
        String folderPath = "/Users/ecarx/Desktop/出品数据/准入检查/530";
        String fileName = "lgmap_road_adas.geojson";

        List fileList = searchFiles(folderPath, fileName);

        if (fileList.isEmpty()) {
            System.out.println("未找到文件.");
        } else {
            System.out.println("找到" + fileList.size() + "个文件,分别如下所示");
            for (File file : fileList) {
                System.out.println(file.getAbsolutePath());
            }
        }
    }

你可能感兴趣的:(java,list,windows)