Java BufferedReader如何跟踪已读取的行?

Java BufferedReader如何跟踪已读取的行?,java,file-io,readline,bufferedreader,Java,File Io,Readline,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

我从一个文件中读取行,我相信一旦我读取了所有行,我会得到一个异常,因为我的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);
}
//读取文件的第一行
iNumMembers=Integer.parseInt(br.readLine().trim());
//读取文件
而((sLine=br.readLine().trim())!=null){
//提取名称和值“m”
字符串[]split=sLine.split(\\s+);
sAccuser=split[0];
iM=Integer.parseInt(拆分[1]);
SATHEACUSED=新字符串[iM];
for(int i=0;i
内部的for循环必须读取几行,因此如果读取了文件的最后一行,则while将尝试
readLine()
,这将失败,因为整个文件都已读取。那么
BufferedReader readLine()
是如何工作的,我如何安全地退出while循环呢

谢谢。

readLine()
在EOF上返回null,您正试图在null引用上调用
trim()
。将调用移动到循环内部的
trim()
,如中所示

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

    // extract the name and value 'm'
    String[] split = sLine.trim().split("\\s+");

事实上,我刚刚意识到我正在使用正则表达式忽略空白。。。所以trim()是无用的,对吗?不,如果输入有前导空格,那么结果数组将包含一个空字符串作为第一个元素(索引[0])。如果不希望出现这种行为,则仍必须修剪()。如果这似乎不合逻辑,考虑一下,如果分隔符是逗号,并且你正在分割字符串“a,b,c”,你会想要什么。在这种情况下,您可能想知道第一个“字段”是空的。