Gam*_*uru -3 java bufferedreader java-8
我有要在我的应用程序中读取的 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.
Run Code Online (Sandbox Code Playgroud)
这是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
Run Code Online (Sandbox Code Playgroud)
输出:
[header]
key=value
[header2]
key1=value1
key2=value2
[header3]
key=value
//whitespace
//whitespace
Run Code Online (Sandbox Code Playgroud)
更新:我删除了 ini 文件中的所有换行符,但仍然没有读取整个文件。
除非您没有在这篇文章中包含某些内容,否则逻辑不会卡在循环中......如果您使用的文件看起来与您发布的完全一样,它会打一个空行(因为您只跳过 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]);
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我这样做是line.contains("=")为了#跳过空白行和开头的行...
| 归档时间: |
|
| 查看次数: |
91 次 |
| 最近记录: |