我必须计算文件中的行,但后来在代码中我还必须打印该文件中的内容,但我不能使用读取器两次它只是说null。如何在不创建一堆bufferedreader对象的情况下解决这个问题? 感谢
答案 0 :(得分:0)
答案 1 :(得分:0)
尝试关闭缓冲区,然后重新打开它。
BufferedReader bufferedReader = new BufferedReader(new FileReader("src/main/java/com/william/sandbox/stackoverflow/samples20160306/Demo.java"));
String line = bufferedReader.readLine();
int lineCount = 0;
while(line != null){
lineCount += 1;
line = bufferedReader.readLine();
}
System.out.println("Line count is: " + lineCount);
bufferedReader.close();
bufferedReader = new BufferedReader(new FileReader("src/main/java/com/william/sandbox/stackoverflow/samples20160306/Demo.java"));
line = bufferedReader.readLine();
while(line != null){
System.out.println(line);
line = bufferedReader.readLine();
}
}
答案 2 :(得分:-1)
您可以使用BufferedReader
的{{1}}和mark()
方法跳回特定位置。
reset()
请注意,try (BufferedReader r = new BufferedReader(new FileReader("somefile.txt"))) {
// marks this position for the next 10 characters read
// after that the mark is lost
r.mark(10);
// do some reading
// jump back to the mark
r.reset();
}
支持标记但不支持所有BufferedReader
。您可以使用Reader
进行检查。