递归搜索文件

 1 public static void main(String[] args) {
 2         searchFile(new File("F:/"), "logFile-data.log");
 3     }
 4 
 5     private static void searchFile(File file,String fileName) {
 6         //  判断 file 是否是目录
 7         if (file != null && file.isDirectory()) {
 8             //  提取当前文件下的一级目录
 9             File[] files = file.listFiles();
10             //  判断是否存在一级目录,存在才可遍历
11             if (files != null && files.length > 0){
12                 //  遍历文件下的目录
13                 for (File f : files) {
14                     //  判断当前遍历的一级目录是 文件还是目录(文件夹)
15                     if (f.isFile()){
16                         //  是否是要找的,是就输出路径
17                         if (f.getName().contains(fileName)){
18                             System.out.println("找到文件在:" + f.getAbsolutePath());
19 //                            //    启动 xxx.exe 程序
20 //                            Runtime runtime = Runtime.getRuntime();//   启动 xxx.exe 程序
21 //                            try {
22 //                                runtime.exec(f.getAbsolutePath());
23 //                            } catch (IOException e) {
24 //                                throw new RuntimeException(e);
25 //                            }
26                         }
27                     }else {
28                         //  是文件夹就继续寻找
29                         searchFile(f,fileName);
30                     }
31                 }
32             }
33         }else {
34             System.out.println("当前搜索的位置不是文件夹");
35         }
36     }

 

posted @ 2024-01-27 22:55  小※兽  阅读(27)  评论(0)    收藏  举报