1. 使用java 递归方法获取指定文件的list,相当于在一个文件夹以及子文件夹,搜索文件的功能。
直接上代码:
public static List<File> searchFiles(String folderPath, String fileName) {
List<File> 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<File> 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<File> 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编程语言编写一个递归方法,功能是在给定的文件夹及其所有子文件夹中搜索具有特定名称的文件。方法首先检查文件夹是否存在,然后递归遍历每个子文件夹,将匹配到的文件添加到列表中。在主函数中,如果找不到匹配的文件,则输出相应消息,否则列出所有找到的文件路径。
858

被折叠的 条评论
为什么被折叠?



