在while循环中使用的BufferedReader readLine [英] BufferedReader readLine used in while loop

查看:305
本文介绍了在while循环中使用的BufferedReader readLine的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到BufferedReader使用while循环来遍历文件的内容,其代码大致如下:

 尝试{
FileReader fr = new FileReader(file);
Buffered Reader br = new BufferedReader(fr);
字符串行;

while((line = br.readLine())!= null){
//做某事
}
} catch(){}

我不了解的是while循环如何在内部递增其计数器,直到它读取了文件。对我来说,上面的while循环意味着如果第一行(line [0])不为空,则执行某项操作(可能无数次),并且永远不要前进到文档的第一行。我对BufferedReader或.readLine()方法不了解什么?

解决方案

我希望我能正确回答您的问题。您想知道BufferedReader如何确定在循环中在没有计数变量的情况下继续读取吗?



如果您查看 BufferedReader.class, 您将看到一个 private int pos; 计数器,该计数器每次从流中读取一个char时都会增加在 public int read()中。 readLine()中也发生了同样的事情,不同之处在于, pos 递增直到行尾。 / p>

您可以使用 reset()函数重置内部计数器(这是最后一个标记位置,请参见此处以获取详细信息)。


I have seen BufferedReader using while loops to iterate through the contents of a file, with code more or less like:

try {
   FileReader fr = new FileReader(file);
   Buffered Reader br = new BufferedReader(fr);
   String line;

   while ( (line = br.readLine()) != null ) {
      // do something
   } 
} catch () {}

what I don't understand is how the while loop is internally incrementing its counter until it has read all lines in the document. To me, the while loop above means "if the first line (line[0]) is not null, do something (presumably an infinite number of times)", and never advancing past the first line of the document. What am I not understanding about BufferedReader or the .readLine() method?

解决方案

I hope I get your question right. You would like to know how BufferedReader determines where to continue reading within the loop without a counting variable?

If you take a look inside BufferedReader.class you will see a private int pos; counter that is incremented every time a char is read from the stream, e.g. in public int read(). Same is happening in readLine() with the difference that pos is incremented until the end of the line is reached.

You can reset the internal counter using reset() function (this is to the last mark location, see here for details).

这篇关于在while循环中使用的BufferedReader readLine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆