BufferedReader 如何跟踪已读取的行?

发布于 2024-09-11 16:15:29 字数 1044 浏览 2 评论 0原文

我正在从文件中读取行,并且我相信一旦读取了所有行,我就会因为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

静谧 2024-09-18 16:15:29

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+");

readLine() returns null on EOF, and you are trying to call trim() on a null reference. Move the call to trim() inside the loop, as in

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

    // extract the name and value 'm'
    String[] split = sLine.trim().split("\\s+");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文