2014-09-02 109 views
-1

我目前有一個Java程序,它循環瀏覽Windows機器上的目錄中的數百個文件,在每個文件中搜索字符串。Wild Card在Java中搜索文件系統文件夾

我這樣做是爲了從200多個文件名中創建一個數組,並且程序執行沒有問題。

我想知道,如果可能要麼

A.使用通配符所以每次我改變我尋遍我不要的文件時必須列出了200多個文件,在我的代碼的數組。

B只搜索特定文件夾內的所有文件。

下面是我的代碼,其中inputFile是文件數組。

try { 
      br = new BufferedReader(new FileReader(inputFile[i])); 
      try { 
       while((line = br.readLine()) != null) 
       { 
        countLine++; 
        //System.out.println(line); 
        String[] words = line.split(" "); 

        for (String word : words) { 
         if (word.equals(inputSearch)) { 
          count++; 
          countBuffer++; 
         } 
        } 

        if(countBuffer > 0) 
        { 
         countBuffer = 0; 
         lineNumber += countLine + ","; 
        } 

       } 
       br.close(); 
+0

A. [是](http://stackoverflow.com/questions/1384947/java-find-txt-files-in-specified-folder)。 B. [是](http://stackoverflow.com/questions/794381/how-to-find-files-that-match-a-wildcard-string-in-java)。 – RossC 2014-09-02 13:03:56

+0

也許正在監視文件系統更改效率更高: http://docs.oracle.com/javase/tutorial/essential/io/notification.html – mariusm 2014-09-02 13:07:55

回答

0

有一種方法listFiles()其中列出了在給定的目錄中的所有File秒。

File directory = new File(-Path to directory-); 
File[] files = directory.listFiles(); 

然後你可以重複一遍。但請注意,在讀取文件之前,listFiles()還會提取所有需要檢查的子文件夾。

+0

工作正常。謝謝....我可能會漏掉一些顯而易見的東西,但我怎麼知道該方法用於文件的順序?我無法確定它是如何訂購這些文件的。 – user2941841 2014-09-02 13:57:16

+0

根據[文檔](http://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles%28%29):'不能保證名稱字符串在結果數組中將以任何特定順序出現;他們並不特別保證按字母順序出現。「 – QBrute 2014-09-02 23:39:38