I am getting StringIndexOutOfBoundsException
for the following code. Here is the error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:694)
at Reflector.readConfig(Reflector.java:103)
at Reflector.run(Reflector.java:48)
at Reflector.main(Reflector.java:419)
Here is code
public int readConfig() {
// validate the contents of the config file
BufferedReader input=null;
String name=null;
String value=null;
String inputLine=null;
dest=new Hashtable();
// open and read the config file
try {
input = new BufferedReader(new FileReader("reflector.conf"));
inputLine=input.readLine();
} catch (IOException e) {
System.err.println("Error reading reflector.conf.");
return(-1);
}
// loop until entire config file is read
while (inputLine != null) {
// skip comments:
if (inputLine.charAt(0) != '#') {
// extract a name/value pair, and branch
// based on the name:
StringTokenizer tokenizer =
new StringTokenizer(inputLine,"=");
name = tokenizer.nextToken();
value = tokenizer.nextToken();
if (name == null) {
System.out.println("no name");
continue;
} else if (name.equals(MODE)) {
if (setMode(value) != 0) {
System.err.println("Error setting mode to " + value);
return(-1);
}
}
} else {
System.err.println("Skipping invalid config file value: "
+ name);
}
}
// read next line in the config file
try {
inputLine=input.readLine();
} catch (IOException e) {
System.err.println("Error reading reflector.conf.");
return(-1);
}
}
// close the config file
try {
input.close();
} catch (IOException e) {
System.err.println("Error closing reflector.conf.");
return(-1);
}
// validate that the combined contents of the config file
// make sense
if (! isConfigValid()) {
System.err.println("Configuration file is not complete.");
return(-1);
}
return(0);
}
Maybe here:
You refer to first element and don't check wheter string has at least one. You should check before wheter this string is not empty.
You have an empty line somewhere in the config file and thus the check
if(inputLine.charAt(0) != '#')
throws the exception. Keep in mindreadLine()
does not read the end of line character.To fix the problem add explicit check to skip empty lines. Easiest fix is to do something like:
I think the problem is here:
You are trying to compare the character at
0
index, but the variableinputLine
may be having an empty string""
,so you also need to check this condition
inputLine.length() != 0