views:

83

answers:

4

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
A: 

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()

kostja
A: 

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.

Gadolin
A: 

Here is an example of how to do it using BufferedReader link text

Suresh Kumar
+2  A: 

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. 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.");
}
fabstab