2014/07/12

[Java] 搜尋目錄下所有深度的檔案 用關鍵字篩選




得到當前目錄:

?
13
String nowDir = new String(System.getProperty("user.dir"));

以下列作為判斷做遞迴

?
25
27
File nowFile = new File(dir);
nowFile.isDirectory();

列出當前資料夾下的file清單

?
28
File[] filelist = nowFile.listFiles();

Example:
要求使用者輸入關鍵字,會找到當前目錄下所有深度的檔案名稱有此關鍵字的檔案。
別列出其絕對路徑。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package p3;
import java.io.File;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class P5 {
    public static void main(String args[]){
        String loopString = new String("yes");
        Scanner scanner = new Scanner(System.in);
        String keyword = new String();
        String nowDir = new String(System.getProperty("user.dir"));
        while (!loopString.equals("no")) {
            System.out.print("Search Content: ");
            keyword = scanner.nextLine().trim();
            System.out.println("ok.");
            getDir(nowDir,keyword);
            System.out.print("continue? (yes or no): ");
            loopString = scanner.nextLine().trim();
        }
        System.out.println("exit");
    }
    public static void getDir(String dir, String keyword){
        File nowFile = new File(dir);
        try {
            if (nowFile.isDirectory()) {
                File[] filelist = nowFile.listFiles();
                for (int i = 0; i < filelist.length; i++) {
                    if (filelist[i].isDirectory()) {
                        //System.out.println(filelist[i].getPath());
                        getDir(filelist[i].getPath(),keyword);
                    }
                }
                for (int i = 0; i < filelist.length; i++) {
                    if (filelist[i].isFile()) {
                        String str = new String(filelist[i].getName());
                        Pattern pattern = Pattern.compile(keyword);
                        Matcher matcher = pattern.matcher(str);
                        while (matcher.find()) {
                            System.out.print(filelist[i].getName()+"\t"+filelist[i].getPath()+"\n");
                        }
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            System.out.print(e);
        }
    }
}