1

我正在从文件中读取行,并且我相信一旦读取了所有行,由于我的 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 循环?

谢谢。

4

1 回答 1

2

readLine()在 EOF 上返回 null,并且您正在尝试调用trim()null 引用。将调用移动到trim()循环内部,如

// read file
while ((sLine = br.readLine()) != null) {

    // extract the name and value 'm'
    String[] split = sLine.trim().split("\\s+");
于 2010-07-28T20:26:49.167 回答