BufferedReader 如何跟踪已读取的行?
我正在从文件中读取行,并且我相信一旦读取了所有行,我就会因为 while 循环条件而得到异常。
Exception in thread "main" java.lang.NullPointerException
at liarliar.main(liarliar.java:79)
...代码...
// read the first line of the file
iNumMembers = Integer.parseInt(br.readLine().trim());
// read file
while ((sLine = br.readLine().trim()) != null) {
// extract the name and value 'm'
String[] split = sLine.split("\\s+");
sAccuser = split[0];
iM = Integer.parseInt(split[1]);
saTheAccused = new String[iM];
for (int i = 0; i < iM; i++) {
saTheAccused[i] = br.readLine().trim();
}
// create member
// initialize name and number of members being accused
Member member = new Member();
member.setName(sAccuser);
member.setM(iM);
member.setAccused(saTheAccused);
veteranMembers.add(member);
}
内部的 for 循环必须读取几行,因此如果读取了文件的最后一行,那么 while 将尝试 readLine()
并且会失败,因为整个文件已被读取。那么 BufferedReader readLine() 是如何工作的以及如何安全地退出 while 循环?
谢谢。
I'm reading lines from a file, and I believe that once I've read all the lines, I get an exception because of my while loop condition.
Exception in thread "main" java.lang.NullPointerException
at liarliar.main(liarliar.java:79)
... the code...
// read the first line of the file
iNumMembers = Integer.parseInt(br.readLine().trim());
// read file
while ((sLine = br.readLine().trim()) != null) {
// extract the name and value 'm'
String[] split = sLine.split("\\s+");
sAccuser = split[0];
iM = Integer.parseInt(split[1]);
saTheAccused = new String[iM];
for (int i = 0; i < iM; i++) {
saTheAccused[i] = br.readLine().trim();
}
// create member
// initialize name and number of members being accused
Member member = new Member();
member.setName(sAccuser);
member.setM(iM);
member.setAccused(saTheAccused);
veteranMembers.add(member);
}
The for loop inside will have to read several lines so if the last line of the file is read, then the while will try to readLine()
and that will fail because the whole file has been read. So how does the BufferedReader readLine()
work and how can I safely exit my while loop?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
readLine()
在 EOF 上返回 null,并且您尝试在 null 引用上调用trim()
。将调用移至循环内的trim()
,如下所示readLine()
returns null on EOF, and you are trying to calltrim()
on a null reference. Move the call totrim()
inside the loop, as in