I need to search for up to 3 words, separated ;
within several files that are located on a web server.
Code:
package prueba.de.buscar.dentro.de.un.archivo;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class PruebaDeBuscarDentroDeUnArchivo {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
java.util.Scanner scanner = new Scanner(System.in);
System.out.println("Introduce una cadena de texto a buscar: ");
String request = scanner.next();
try {
final BufferedReader reader = new BufferedReader(
new FileReader("C:\\Users\\ProKode\\Downloads\\archivo.txt")
);
String line = "";
while((line = reader.readLine())!= null) {
if(line.indexOf(";")!= -1){
if (line.split(";")[0].equalsIgnoreCase(request)) {
System.out.println("Se encontro la palabra "+ request);
}
}
}
reader.close();
} catch (FileNotFoundException e) {e.printStackTrace();
} catch (IOException e) {e.printStackTrace();}
}
}
But I get this error:
Exception in thread
main
java.lang.ArrayIndexOutOfBoundsException
: 0at
prueba.de.buscar.dentro.de.un.archivo.PruebaDeBuscarDentroDeUnArchivo.main(PruebaDeBuscarDentroDeUnArchivo.java:23
)Java Result: 1
BUILD SUCCESSFUL (total time: 10 seconds)
This is line 23:
if(line.indexOf(";") != -1)
The content of the file is (it is an example):
Departure:
Enter a text string to search for:
moises;diego;user
The word was found: moses.
The word was found: diego.
Found the word: user.
NOTE: CAPITAL LETTERS DO NOT MATTER.
You should not get a
ArrayIndexOutOfBoundsException
in the indicated line, because in this line there is no method that could throw one.If you change this code:
by
You should get an array of size > 0 for sure.
In the search with
split
, a limit n > 0 limits the number of results to n , a limit of n=-1 gives you all possible results with a minimum of the entire String if the pattern is not found. n=0 behaves like n=-1 with the difference that strings are eventually discarded.So far I can't reproduce one
ArrayIndexOutOfBounds
with any of the lines of code in the indicated part, using permutations of String without ";" even "".Seeing as I can't reconstruct the error, let's use safer code:
To search for the word in up to 3 words separated by ";" you use:
Update
With the update of the question with clarification that is sought, the necessary code is changed a bit:
I implemented the solution using the methods you also used (
split
andindexOf
). There was an alternative of processing the lines of your file with a regular expression usingPattern
andMatcher
which would be a bit more elegant (based on feedback).I think it would be easier if you directly look up the words on each line. Instead of:
Try this:
java.lang.ArrayIndexOutOfBoundsException
means that you tried to access an array position that does not exist (a negative number, or a number greater than the size of the array - 1 * )The index you tried to access is
0
, which means that the array has no elements (line.split(";").length == 0
). This happens because the line simply doesn't have any ";" (possibly you have a blank line at the end of the file).The most normal thing would be to check those conditions; for instance.
!line.trim().isEmpty()
) before doing the split.String[] palabras = line.split(";");
and check its size (palabras.length > 0
) before trying to access element 0.In both cases, you should decide how the program will behave: you can either just ignore the line or inform the user of a runtime error ("Found a line without ';', line content is " + line).
* As in C, array indices start at 0, so valid values are from
0
to[tamaño del array - 1]
.