【问题标题】:Java: How to search files for a keyword? [closed]Java:如何在文件中搜索关键字? [关闭]
【发布时间】:2013-03-20 18:17:17
【问题描述】:

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

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

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

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

编辑:

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

【问题讨论】:

  • 这是一个读取文件的简洁示例:stackoverflow.com/a/3806154/16959
  • 当然如果你想读取一个文件的文本内容,看看tika.apache.org,它是一个可以从Word Docs,网页中提取文本的库(避免HTML标签), PDF等
  • 虽然在 Java 中很可能做到这一点,但您是否考虑过(取决于您的要求)使用标准命令行工具之一来做到这一点?例如,UNIX grep 实用程序完全可以满足您的需要。
  • 我知道 grep 但我需要它在 Java 中
  • 为什么需要用 Java 做 - 这是作业吗?

标签: java


【解决方案1】:
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.");
}

【讨论】:

  • 你能说得这么清楚吗?格式和东西
  • @jsn 字节在搜索关键字之前转换为字符串。所以这不是问题。
  • 我需要下载 Pattern 吗?
  • 导入 java.util.regex.*;
  • 把正确的路径放到目录中。并将关键字替换为您的关键字。
【解决方案2】:

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

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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多