2012-01-10 42 views
0

我用Java編寫一個程序來搜索某一段文字這兩種創建文件的方式是一樣的嗎?

的我拿着這3個作爲輸入

  1. 的目錄,從那裏搜索應該開始
  2. 文本要搜索
  3. 如果搜索必須是遞歸的(或不包括目錄內的目錄)

這裏是我的代碼

public void theRealSearch(String dirToSearch, String txtToSearch, boolean isRecursive) throws Exception 
{ 
    File file = new File(dirToSearch); 
    String[] fileNames = file.list(); 
    for(int j=0; j<fileNames.length; j++) 
    { 
     File anotherFile = new File(fileNames[j]); 
     if(anotherFile.isDirectory()) 
     { 
      if(isRecursive) 
       theRealSearch(anotherFile.getAbsolutePath(), txtToSearch, isRecursive); 
     }  
     else 
     { 
      BufferedReader bufReader = new BufferedReader(new FileReader(anotherFile)); 
      String line = ""; 
      int lineCount = 0; 
      while((line = bufReader.readLine()) != null) 
      { 
       lineCount++; 
       if(line.toLowerCase().contains(txtToSearch.toLowerCase())) 
        System.out.println("File found. " + anotherFile.getAbsolutePath() + " at line number " + lineCount); 
      } 
     } 
    } 
} 

當遞歸設置爲true,則程序將返回FileNotFoundException異常

所以,我所提到的網站,從那裏我得到了主意,實施這一方案,並編輯我的程序一點。這是怎麼回事

public void theRealSearch(String dirToSearch, String txtToSearch, boolean isRecursive) throws Exception 
{ 
    File[] files = new File(dirToSearch).listFiles(); 
    for(int j=0; j<files.length; j++) 
    { 
     File anotherFile = files[j]; 
     if(anotherFile.isDirectory()) 
     { 
      if(isRecursive) 
       theRealSearch(anotherFile.getAbsolutePath(), txtToSearch, isRecursive); 
     }  
     else 
     { 
      BufferedReader bufReader = new BufferedReader(new FileReader(anotherFile)); 
      String line = ""; 
      int lineCount = 0; 
      while((line = bufReader.readLine()) != null) 
      { 
       lineCount++; 
       if(line.toLowerCase().contains(txtToSearch.toLowerCase())) 
        System.out.println("File found. " + anotherFile.getAbsolutePath() + " at line number " + lineCount); 
      } 
     } 
    } 
} 

它的工作完美。這兩個片段之間的唯一區別是創建文件的方式,但它們對我來說看起來是一樣的!

任何人都可以指出我在哪裏搞砸了嗎?

回答

-1

您需要在@fivedigit指出的構建File對象時包含基目錄。

File dir = new File(dirToSearch); 
for(String fileName : file.list()) { 
    File anotherDirAndFile = new File(dir, fileName); 

,完成後我將關閉您的文件和我會避免使用throws Exception

+0

這就是爲什麼我經常在嘗試調試程序時建議使用調試器的原因。如果你仔細查看代碼,你會發現目錄名稱從文件' – 2012-01-10 09:32:19

+0

中缺少... – Sphinx 2012-01-10 09:38:59

1

在第二個例子中,它使用listFiles()來返回文件。在你的例子中它使用了list(),它只返回文件的名字 - 這裏是錯誤。

+0

使用文件名,我在for循環中創建了文件。在兩個版本的代碼中,文件是以一種或另一種方式創建的? 你能詳細解釋一下你的答案嗎? – Sphinx 2012-01-10 09:17:55

+0

list()返回文件的名稱,而不是洞的路徑 - 所以當你創建文件時,它將不起作用 – xyz 2012-01-10 09:22:59

+0

現在我明白了。搜索正在執行錯誤的目錄 – Sphinx 2012-01-10 09:35:15

1

第一個示例中的問題是file.list()返回文件NAMES數組,而不是路徑。如果你想解決這個問題,在創建文件時,只需通過file作爲參數,因此它被用作父文件:

File anotherFile = new File(file, fileNames[j]); 

現在假定anotherFile是由file代表的目錄,它應該工作。

+0

哦!它現在非常有意義。我的程序實際上是搜索使用fileNames []級別創建的文件(即在目錄的父目錄中) 現在我明白了,它錯過了它似乎太小(有這種感覺很多次! !) – Sphinx 2012-01-10 09:32:55

相關問題