【问题标题】:Searching for string in a delimited text File [closed]在分隔的文本文件中搜索字符串 [关闭]
【发布时间】:2012-01-11 14:43:17
【问题描述】:

假设我有一个字符串 =“你好”。如何打开一个文本文件并检查该文本文件中是否存在 hello?

文本文件的内容:

hello:man:yeah

我尝试使用下面的代码。文件阅读器是否只读取第一行?我需要它检查所有行以查看 hello 是否存在,如果存在,则从中取出“man”。

try {
    BufferedReader in = new BufferedReader(new FileReader("hello.txt"));
    String str;
    while ((str = in.readLine()) != null) {
        System.out.println(str);
    }
} catch (IOException e) {
    System.out.println("Error.");
}

【问题讨论】:

  • String myArray[] = str.split(":"); java String 类中有很多方法可以处理这类事情。
  • 您的文件只包含一行...所以 readline 在读取该行时退出循环,因为第二次 in.readline 返回 null
  • 您对BufferedReader 的使用似乎是正确的。你没有看到“hello.txt”的逐行输出吗?
  • 我的文本文件不止一行,我这里只显示一行。有没有更好的方法来检查一个字符串“hello”是否在文本文件中?

标签: java file input csv


【解决方案1】:

如果 hello:man:yeah 是您文件中的一行,那么您的代码工作正常。 readLine() 将读取一行,直到找到换行符(在这种情况下为一行)。

如果你只是想看看它是否在文件中,那么你可以这样做:

 String str;
 boolean found = false;
 while ((str = in.readLine()) != null) {
       if(str != null && !found){
         found = str.contains("hello") ? true : false;
       }
    }

如果您需要进行全词搜索,则需要使用正则表达式。用 \b 包围您的搜索文本将执行整个单词搜索。这是一个 sn-p(注意,StringUtils 来自 Apache Commons Lang):

    List<String> tokens = new ArrayList<String>();
    tokens.add("hello");

    String patternString = "\\b(" + StringUtils.join(tokens, "|") + ")\\b";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(text);

    while (matcher.find()) {
        System.out.println(matcher.group(1));
    }

当然,如果你没有多个令牌,你可以这样做:

String patternString = "\\bhello\\b";

【讨论】:

  • 嗨,谢谢。使用 String.contains,即使输入是“地狱”,它也会返回 true。我需要它是准确的。
  • 我从这里提取了关于字符串匹配的内容:stackoverflow.com/questions/5091057/….
【解决方案2】:

使用String.indexOf()String.contains() 方法。

【讨论】:

    【解决方案3】:

    在每一行上使用String.contains 方法。每一行都在 while 循环中处理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 1970-01-01
      • 2018-09-29
      • 2016-10-25
      • 1970-01-01
      相关资源
      最近更新 更多