我正在阅读一个看起来像这样的文本文件(见下图)
但是当我使用下面的源代码阅读文本文件时。它跳过一些线(见下图)
注意它只显示该序列中的a1,a3,a5,a7。
下面是我的代码,它没有做任何特别的事情,只需读取文本文件并将其保存在Map中。
public static Map<String,Boolean> readSaveBoardState(){
BufferedReader buffRead = null;
Map<String, Boolean> scannedSavedState = new TreeMap<String, Boolean>();
try{
buffRead = new BufferedReader( new FileReader(saveCurrentState));
String position = buffRead.readLine();
while (buffRead.readLine() != null){
String[] splitDash = position.split("-");
System.out.println(splitDash[0] + " "+ splitDash[1]);
scannedSavedState.put(splitDash[0], Boolean.parseBoolean(splitDash[1]));
position = buffRead.readLine();
}
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
try {
buffRead.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return scannedSavedState;
}
我现在已经看了30分钟了,我仍然不知道为什么这样做。任何人都可以帮助,谢谢。
答案 0 :(得分:7)
在您的代码中,您阅读了2行,但仅使用了一行:
while (buffRead.readLine() != null){ // read a line
String[] splitDash = position.split("-");
System.out.println(splitDash[0] + " "+ splitDash[1]);
scannedSavedState.put(splitDash[0], Boolean.parseBoolean(splitDash[1]));
position = buffRead.readLine(); // read the second line
}
更改为:
while ((position =buffRead.readLine()) != null){ // read a line
String[] splitDash = position.split("-");
System.out.println(splitDash[0] + " "+ splitDash[1]);
scannedSavedState.put(splitDash[0], Boolean.parseBoolean(splitDash[1]));
}
答案 1 :(得分:1)
您正在读取两次行,但只存储一次值。
while (buffRead.readLine() != null){ // read here and ignore
String[] splitDash = position.split("-");
System.out.println(splitDash[0] + " "+ splitDash[1]);
scannedSavedState.put(splitDash[0], Boolean.parseBoolean(splitDash[1]));
position = buffRead.readLine(); // read here and use
}
答案 2 :(得分:0)
你在循环中调用readLine()2次:第一次在while循环条件下,第二次在循环结束时。第一次调用的输出被丢弃,因为它永远不会被赋予任何变量。 这应该有效:
String position = buffRead.readLine();
while (position != null){
...
position = buffRead.readLine();
}