java - 在 Java 中读取文件时如何摆脱 Invalid Mark 错误?
问题描述
我正在尝试读取文件,但运行代码时出现 IOException: Invalid mark 错误,即使它在异常之前输出正确的结果。如果我增加标记的值(到 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
解决方案
int 参数mark()
表示要存储在缓冲区中的字符/字节数。如果您读取了太多超过标记大小的数据,那么mark
将是invalidated
. 并且在调用reset()
时,它将给出该异常。
如果您阅读文档reset()
,它会说它抛出:
IOException - If the stream has never been marked,or if the mark has been invalidated
您可以通过增加标记参数的容量来修复您的代码。
br.mark(1000); // 1000 or depending on your buffer.
完整代码:
private static void readEventsFile2() throws FileNotFoundException, IOException {
ArrayList<String> evtList = new ArrayList<>();
FileReader fr = new FileReader("C:\\Users\\Abi.Shaquib\\Desktop\\overflow.txt");
BufferedReader br = new BufferedReader(fr);
String a = "";
while ((a = br.readLine()) != null) {
if (isNum(a)) {
int 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(1000);
a = br.readLine();
if (a == null || isNum(a)) {
System.out.println(evtList);
evtList.clear();
}
br.reset();
}
}
输出:
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]
推荐阅读
- c# - Unity 网格对撞机问题。球体穿过网格
- vue.js - 外部分页 vuetify 数据表
- elasticsearch - 使用 NEST 在 Elasticsearch 中嵌套对象
- angular - ionic v4 和社交分享插件
- multithreading - __sync_bool_compare_and_swap - 如果 oldval 和 newval 相同则返回值
- power-automate - 您可以使用 Microsoft Power Automate 开发公司范围的工作流解决方案吗?
- flutter - 当我的应用上传到 CH Play 时如何更新版本
- c++ - 有人可以解释一下这个矩阵求幂函数是如何工作的吗?
- java - jsp包含另一个jsp与Struts2,但没有结果
- json - 从 api 检索数据时出现此错误?