如何在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);}
name.txt 看起来像这样:
1
a
0
2
b
0
how to search for a certain word in a text file in 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:
1
a
0
2
b
0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的代码期望文件中的每一行都包含三个以空格分隔的单词。因此,您的文件必须如下所示:
如果文件中的某一行不包含三个空格分隔的单词,则会发生 ArrayIndexOutOfBoundsException。例如,您的文件中可能有一个空行。
您可以在代码中检查这一点,如下所示:
Your code expects each line in the file to have three space-separated words. So your file must look like this:
The
ArrayIndexOutOfBoundsException
occurs if there is a line in the file that does not have three space-separated words. For example, there might be an empty line in your file.You could check this in your code like this:
您可以使用此处描述的模式/匹配器组合< /a>,或尝试扫描程序。像这样使用缓冲读取器:
并使用
in.toString()
提取字符串You can use the Pattern/Matcher combination described here, or try the Scanner. Use the Buffered reader like this :
and extract the string with
in.toString()
如果文本很大并且您不想立即阅读并保留在内存中。您可以不断地使用 readLine() 读取一行,并在每个输出行中搜索模式。
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.
这是如何使用 BufferedReader 执行此操作的示例
链接文本
Here is an example of how to do it using BufferedReader
link text