简体   繁体   English

如何在Java中的文本文件中搜索特定单词

[英]how to search for a certain word in a text file in java

how to search for a certain word in a text file in java? 如何在Java的文本文件中搜索某个单词? Using buffered reader, I have this code, but I get a 使用缓冲的阅读器,我有这段代码,但是我得到了

java.lang.ArrayIndexOutOfBoundsException

Please help me determine what's wrong with my program. 请帮助我确定程序有什么问题。

System.out.println("Input name: ");
      String tmp_name=input.nextLine();


        try{

             FileReader fr;
      fr = new FileReader (new File("F:\\names.txt"));
      BufferedReader br = new BufferedReader (fr);
String s;
while ((s = br.readLine()) != null) {

String[] st = s.split(" ");
String idfromtextfile=st[0];
String nemfromtextfile = st[1];
String scorefromtextfile=st[2];


if(nemfromtextfile.equals(tmp_name)){
    System.out.println("found");      
}else{
    System.out.println("not found");
}



      }

  }catch(Exception e){ System.out.println(e);}

names.txt looks like this: names.txt看起来像这样:

1
a
0

2
b
0

Your code expects each line in the file to have three space-separated words. 您的代码期望文件中的每一行包含三个以空格分隔的单词。 So your file must look like this: 因此,您的文件必须如下所示:

1 a 0
2 b 0

The ArrayIndexOutOfBoundsException occurs if there is a line in the file that does not have three space-separated words. 如果文件中的一行没有三个以空格分隔的单词,则会发生ArrayIndexOutOfBoundsException For example, there might be an empty line in your file. 例如,您的文件中可能有一个空行。

You could check this in your code like this: 您可以像下面这样在代码中进行检查:

if ( st.length != 3) {
    System.err.println("The line \"" + s + "\" does not have three space-separated words.");
}

You can use the Pattern/Matcher combination described here , or try the Scanner . 您可以使用此处描述的图案/匹配器组合,或尝试使用扫描仪 Use the Buffered reader like this : 这样使用缓冲读取器:

BufferedReader in
   = new BufferedReader(new FileReader("foo.in"));

and extract the string with in.toString() 并使用in.toString()提取字符串

If text is huge and you don't want to read it at once and keep in memory. 如果文本很大,并且您不想一次阅读并保留在内存中。 You may constantly read a line with readLine(), and search each of the output line for a pattern. 您可以不断使用readLine()读取一行,并在每个输出行中搜索一个模式。

这是一个使用BufferedReader 链接文本的方法示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM