【发布时间】:2020-11-10 10:27:31
【问题描述】:
我正在尝试读取文件,但运行代码时却收到 IOException: Invalid mark error,即使它在异常之前输出了正确的结果。如果我增加标记的值(到 40 左右),它会产生完整且正确的输出,但会出现 NullPointerException。
这是我的代码:
private static void readEventsFile2() throws FileNotFoundException, IOException {
ArrayList<String> evtList = new ArrayList<>();
FileReader fr=new FileReader("src/idse/Events.txt");
BufferedReader br = new BufferedReader(fr);
String a ="";
try {
while(!(a=br.readLine()).isEmpty()) {
if (isNum(a)){
numEv = Integer.parseInt(a);
System.out.println(numEv);
} else if(!a.isEmpty()){
String[] parts = a.split(":");
for (String part : parts) {
evtList.add(part);
}
}
br.mark(0);
a = br.readLine();
if(a == null || isNum(a)) {
System.out.println(evtList);
evtList.clear();
}
br.reset();
}
} catch (NoSuchElementException | IllegalStateException | NullPointerException e) {
System.out.println(e);
}
}
上述代码的输出(第 149 行是 br.reset()):
5
[Logins, 2, Total time online, 1, Emails sent, 1, Orders processed, 1, Pizza’s ordered online, 0.5]
10
Exception in thread "main" java.io.IOException: Mark invalid
at java.io.BufferedReader.reset(BufferedReader.java:512)
at idse.IDSE.readEventsFile2(IDSE.java:149)
at idse.IDSE.main(IDSE.java:188)
我正在阅读的文件格式:
5
Logins:2:Total time online:1:Emails sent:1:Orders processed:1:
Pizza’s ordered online:0.5:
10
Logins:7:Total time online:5:Emails sent:9:Orders processed:15:
Pizza’s ordered online:0.9:Logouts:6
【问题讨论】:
标签: java bufferedreader