1

我正在尝试编写一个函数,该函数采用关键字并搜索文件列表,然后打印出任何包含该关键字的文件。

到目前为止,我只有一个文件列表和关键字。

File[] files = new File("<directory>").listFiles();
Scanner keyword = new Scanner("hello");

我想现在我需要构建某种形式的循环来遍历文件以查找关键字。任何帮助,即使是易于理解的教程,我们都将不胜感激。

编辑:

这些文件是仅包含一行的文本文件

4

2 回答 2

3
File dir = new File("directory"); // directory = target directory.
if(dir.exists()) // Directory exists then proceed.
{ 
  Pattern p = Pattern.compile("keyword"); // keyword = keyword to search in files.
  ArrayList<String> list = new ArrayList<String>(); // list of files.

  for(File f : dir.listFiles())
  {
    if(!f.isFile()) continue;
    try
    {
      FileInputStream fis = new FileInputStream(f);
      byte[] data = new byte[fis.available()];
      fis.read(data);
      String text = new String(data);
      Matcher m = p.matcher(text);
      if(m.find())
      {
        list.add(f.getName()); // add file to found-keyword list.
      }
      fis.close();
    } 
    catch(Exception e)
    {
      System.out.print("\n\t Error processing file : "+f.getName());
    }

  }
  System.out.print("\n\t List : "+list); // list of files containing keyword.
} // IF directory exists then only process.
else
{
  System.out.print("\n Directory doesn't exist.");
}
于 2013-03-20T18:25:40.550 回答
0

如果你想使用扫描器类,这里是你如何扫描一个特定关键字的文件:扫描器只不过是一个迭代器,它扫描提供给它的输入。

Scanner s = new Scanner(new File("abc.txt"));
while(s.hasNextLine()){
    //read the file line by line
String nextLine = s.nextLine();
            //check if the next line contains the key word
    if(nextLine.contains("keyword"))
    {
              //whatever you want to do when the keyword is found in the file
               and break after the first occurance is found
             break;
    }
}
于 2013-03-20T19:01:52.037 回答