[英]use bufferedreader on a txt file twice?
i have to count the lines on a file but later in the code I also have to print what's in that file, but I can't use the reader twice it just says null. 我必须计算文件上的行数,但稍后在代码中我也必须打印该文件中的内容,但是我不能使用读取器两次,它只能说为null。 How can I work this out without creating a bunch of bufferedreader objects? 如何在不创建一堆bufferedreader对象的情况下解决此问题? thanks 谢谢
Try closing the buffer, and then re-opening it again. 尝试关闭缓冲区,然后再次重新打开它。
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();
}
}
You can use BufferedReader
's mark()
and reset()
methods to jump back to a specific position. 您可以使用BufferedReader
的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();
}
Note that, BufferedReader
supports marking but not all Reader
s do. 请注意, BufferedReader
支持标记,但并非所有Reader
都支持。 You can use markSupported()
to check. 您可以使用markSupported()
进行检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.