[英]how to search for a certain word in a text file in java
如何在Java的文本文件中搜索某个单词? 使用缓冲的阅读器,我有这段代码,但是我得到了
java.lang.ArrayIndexOutOfBoundsException
请帮助我确定程序有什么问题。
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看起来像这样:
1
a
0
2
b
0
您的代码期望文件中的每一行包含三个以空格分隔的单词。 因此,您的文件必须如下所示:
1 a 0
2 b 0
如果文件中的一行没有三个以空格分隔的单词,则会发生ArrayIndexOutOfBoundsException
。 例如,您的文件中可能有一个空行。
您可以像下面这样在代码中进行检查:
if ( st.length != 3) {
System.err.println("The line \"" + s + "\" does not have three space-separated words.");
}
如果文本很大,并且您不想一次阅读并保留在内存中。 您可以不断使用readLine()读取一行,并在每个输出行中搜索一个模式。
这是一个使用BufferedReader 链接文本的方法示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.