2012-01-10 70 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

相关问题