我正在读取文件中的行,我相信一旦我读完所有行,就会因为我的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循环呢?
感谢。
答案 0 :(得分:2)
readLine()
在EOF上返回null,并且您尝试在空引用上调用trim()
。将调用移至循环内的trim()
,如
// read file
while ((sLine = br.readLine()) != null) {
// extract the name and value 'm'
String[] split = sLine.trim().split("\\s+");