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
Your code expects each line in the file to have three space-separated words. So your file must look like this:
The
ArrayIndexOutOfBoundsExceptionoccurs 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: