【发布时间】:2016-01-03 06:01:06
【问题描述】:
我有一个奇怪的问题,我的代码看起来很好(至少对我来说),但在调试器上,实际结果总是错误的。
首先是代码:
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() 方法返回空值。我不知道问题出在哪里。
我唯一的猜测是我曾经数过它们的.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
作为,现在我最好的朋友Holger mentioned,将直接使用流循环,这样会更整洁。
database.lines().forEach(currentLine -> REGISTRY.add(new Entry(currentLine)));
还有一个班轮!美丽的!在此之后将深入到流世界。
【问题讨论】:
标签: java java-8 bufferedreader