BufferedReader 没有读取整个文件并且没有退出循环

BufferedReader not reading the entire file and not exiting the loop

我有要在我的应用程序中读取的 ini 文件,但问题是它没有读取整个文件,它卡在了 while 循环中。

我的代码:

FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);

String line = br.readLine();
Properties section = null;

while(line!=null){
     if(line.startsWith("[") && line.endsWith("]")){
         section = new Properties();
         this.config.put(line.substring(1, line.length() - 1), section);
     }else{
         String key = line.split("=")[0];
         String value = line.split("=")[1];
         section.setProperty(key, value);
     }

     line = br.readLine();
     System.out.println(line);

     // To continue reading newline. 
     //if i remove this, it will not continue reading the second header
     if(line.equals("")){ 
         line = br.readLine();
     }  
}

System.out.println("Done"); // Not printing this.

这是 ini 文件中的内容。包含换行符,所以我添加 line.equals("").

[header]
key=value

[header2]
key1=value1
key2=value2

[header3]
key=value

// -- stops here

//this newlines are included.


#Some text   // stops here when I remove all the newlines in the ini file.
#Some text

输出:

[header]
key=value
[header2]
key1=value1
key2=value2
[header3]
key=value
//whitespace
//whitespace

更新: 我删除了 ini 文件中的所有换行符,但仍然没有读取整个文件。

除非您没有包含在此 post 中的内容,否则逻辑不会卡在循环中...如果您使用的文件与您使用的文件完全相同 posted,它会命中一个空行(因为你只跳过 1 个空白)或以“#”开头的行之一并得到 ArrayIndexOutOfBoundsException 因为这些行不包含“=”...简化你的 while 循环和 ArrayIndexOutOfBoundsExceptions 不会发生,它将处理整个文件:

    Properties section = null;
    String line = null;
    while ((line = br.readLine()) != null) {
        if (line.startsWith("[") && line.endsWith("]")) {
            section = new Properties();
            this.config.put(line.substring(1, line.length() - 1), section);
        } else if (line.contains("=") && !line.startsWith("#")) {
            String[] keyValue = line.split("=");
            section.setProperty(keyValue[0], keyValue[1]);
        }
    }

请注意,我正在执行 line.contains("=") 以便跳过空行和以 # 开头的行...