我收到StringIndexOutOfBoundsException
以获取以下代码。这是错误
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)
这是代码
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);
}
答案 0 :(得分:2)
配置文件中某处有一个空行,因此检查if(inputLine.charAt(0) != '#')
会抛出异常。请注意,readLine()
不会读取行尾字符。
要解决此问题,请添加显式检查以跳过空行。最容易解决的问题是:
if (!inputLine.isEmpty() && inputLine.charAt(0) != '#') {
答案 1 :(得分:0)
也许在这里:
inputLine.charAt(0)
您指的是第一个元素,并且不检查wheter字符串是否至少有一个。你应该在此字符串不为空之前检查。
答案 2 :(得分:0)
我认为问题在于:
if (inputLine.charAt(0) != '#') {
您正在尝试比较0
索引处的字符,但变量inputLine
可能有一个空字符串""
,
因此您还需要检查此条件inputLine.length() != 0