0

我正在获取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);
}
4

3 回答 3

2

您在配置文件的某处有一个空行,因此检查if(inputLine.charAt(0) != '#')会引发异常。请记住readLine()不读取行尾字符。

要解决此问题,请添加显式检查以跳过空行。最简单的解决方法是执行以下操作:

if (!inputLine.isEmpty() && inputLine.charAt(0) != '#') {
于 2013-02-05T13:06:08.023 回答
0

也许在这里:

inputLine.charAt(0)

您引用第一个元素并且不检查字符串是否至少有一个。您应该在此字符串不为空之前检查。

于 2013-02-05T13:07:55.600 回答
0

我认为问题出在这里:

if (inputLine.charAt(0) != '#') {

您正在尝试比较0索引处的字符,但变量inputLine可能有一个空字符串""

所以你还需要检查这个条件inputLine.length() != 0

于 2013-02-05T13:08:51.667 回答