BufferedReader 还不是 null .readLine() 返回 null

BufferedReader not null yet .readLine() returning null

我有一个奇怪的问题,我的代码看起来很好(至少对我而言),但在调试器上和实际结果总是错误的。

首先是代码:

private void updateRegistry( String filename ){
    BufferedReader database = Init.MANAGER.readFile( Path.getDB(), filename );

    REGISTRY.clear();

    long maxLines = database.lines().count();
    for (int i = 0; i < maxLines; i++) {
        try {
            String currentLine = database.readLine();
            Registry regAdd = new Entry( currentLine );
            REGISTRY.add( regAdd );
        } catch( Exception e ) {
            System.err.println( ERROR.getStackTrace( e ) );
        }
    }
}

因此,循环中的所有 currentLine 个变量总是 returns null.

作为 REGISTRY 在 class 上的常量,即 LinkedList
ERROR另一个报错常量,这个不相关。

我知道 .readLine() 每个方法调用读取一行,使每个调用成为下一行要读取的内容。

此外,通过使用调试器,我可以确认数据正在 BufferedReader 变量中恢复。

然而 .readLine() 方法 returns 无效。我不知道是什么问题。

我唯一的猜测是我用来计算它们的 .lines()。这会使流为空吗?如果这是问题所在,我该如何纠正它,因为我需要行数。

我做错了什么?我调试了一百次,我什么也没给我数据。

编辑:

为了将来参考,我使用了另一个 post 的例子,我更喜欢 while 循环。删除 .lines() 变量和循环后

private void updateRegistry( String filename ){
    BufferedReader database = Init.MANAGER.readFile( Path.getDB(), filename );

    REGISTRY.clear();

    try {
        for ( String currentLine = database.readLine(); currentLine != null; currentLine = database.readLine() ) {
            Registry regAdd = new Registry( currentLine );
            REGISTRY.add( regAdd );
        }
    } catch ( Exception e ){
        System.err.println( ERROR.getStackTrace( e ) );
    }
}

Post Link

感谢您的帮助,现在我可以更快地完成作业了! xD

作为,现在我最好的朋友,,将直接使用流循环,这样会更整洁。

database.lines().forEach(currentLine -> REGISTRY.add(new Entry(currentLine)));

还有一个班轮!美丽的!之后就去流媒体世界了。

BufferedReader.lines():

After execution of the terminal stream operation there are no guarantees that the reader will be at a specific position from which to read the next character or line.

因此,在调用 long maxLines = database.lines().count(); 之后,不能保证您之后可以从同一个 reader 中读取任何行。在典型的实现中,此操作会消耗所有行。

如果你不能重新获取等价物reader,但确实需要事先计数,唯一的选择是缓冲它们,例如将所有行收集到 List like

List<String> list=database.lines().collect(Collectors.toList());

获取大小和内容。


如果不需要事先计数,可以用实际操作代替计数操作:

database.lines().forEach(currentLine -> REGISTRY.add(new Entry(currentLine));

一样,即使没有流 API,您也不需要预先计算,当您想要用它做的就是执行迭代时。

BufferedReader.lines()是Java8中的一个新方法,我不太熟悉。但是,由于您只想依次处理每一行,因此您通常会使用如下内容:

String currentLine = null;
while ((currentLine = database.readLine()) != null) {
    // do processing
}