我有一个奇怪的问题,我的代码看起来很好(至少对我而言),但在调试器上和实际结果总是错误的。
首先是代码:
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
变量始终返回 null
。
作为 REGISTRY
类的一个常量,它是一个 LinkedList
。
和ERROR
另一个常量来报告错误,这是不相关的。
我知道 .readLine()
每个方法调用读取一行,使每次调用成为下一行要读取的内容。
此外,通过使用调试器,我可以确认数据正在 BufferedReader
变量中恢复。
然而 .readLine()
方法返回 null。我不知道问题出在哪里。
我唯一的猜测是我用来计算它们的 .lines()
。这会使流为空吗?如果这是问题所在,我该如何更正它,因为我需要行数。
我做错了什么?我调试了一百次,但我什么也没给我数据。
编辑:
为了将来引用,我使用了另一篇文章的示例,我更喜欢 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 ) );
}
}
感谢您的帮助,现在我可以更快地完成作业了! xD
作为,现在我最好的 friend ,Holger mentioned ,将直接使用流循环,这使它更加整洁。
database.lines().forEach(currentLine -> REGISTRY.add(new Entry(currentLine)));
还有一条线!美丽的!之后将在流世界中停留。
最佳答案
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();
之后,无法保证您之后可以从同一阅读器读取任何行。在典型的实现中,此操作会消耗所有行。
如果你不能重新获取等效的阅读器,但确实需要事先计数,唯一的选择是缓冲它们,例如将所有行收集到 List
中
List<String> list=database.lines().collect(Collectors.toList());
获取大小和内容。
如果事先不需要计数,可以用实际操作代替计数操作:
database.lines().forEach(currentLine -> REGISTRY.add(new Entry(currentLine));
作为danmec has pointed out ,即使没有流 API,您也不需要事先进行计数,因为您只想用它来执行迭代。
关于java - BufferedReader 还不是 null .readLine() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32967933/