(reader.ready())和使用for循环读取文件有什么区别? [英] What's the difference between (reader.ready()) and using a for loop to read through a file?
问题描述
到 while(reader.ready())
。因此:
原始用于
循环:
int numberOfLines = readLines();
numberOfLines = numberOfLines / 6;
(int i = 0; i< numberOfLines; i ++)
更改为:
BufferedReader reader = new BufferedReader(new FileReader(test.dat ));
while(reader.ready())
有什么区别两个,更具体一点, .ready()
是做什么的?
解决方案从 Javadoc :
告诉这个流是否准备好被读取。如果缓冲区不是空的,或者底层字符流已经准备就绪,缓冲字符流就绪。
返回:
如果下一个阅读()保证不会阻塞输入,否则返回false。请注意,返回false并不能保证下一次读取将被阻止。
所以,缓冲区将会是 ready 如果 read
保证不会被阻止。
由于JB Nizet 指出 ,这并不意味着你已经到达了文件的结尾。如果出于任何原因,您的流可能阻塞,那么 ready 将返回 false
。
相反,试试看这样的文件:
字符串行= reader.readLine();
while(line!= null){
//代码代码
line = reader.readLine();
}
In my previous question, I asked about a problem with looping through a file, and solved it. However, I realised that the method failed to read the last set of lines/record. So I changed the original for
loop to a while(reader.ready())
. So:
Original for
loop:
int numberOfLines = readLines();
numberOfLines = numberOfLines / 6;
for(int i=0;i < numberOfLines; i++)
Changed that to:
BufferedReader reader = new BufferedReader(new FileReader("test.dat"));
while(reader.ready())
What's the difference between the two, and a little more specifically, what exactly does the .ready()
do?
解决方案 From the Javadoc:
Tells whether this stream is ready to be read. A buffered character stream is ready if the buffer is not empty, or if the underlying character stream is ready.
Returns:
True if the next read() is guaranteed not to block for input, false otherwise. Note that returning false does not guarantee that the next read will block.
So, the buffer will be ready
if read
is guaranteed not to block.
As JB Nizet points out, this does not necessarily mean that you have reached the end of the file. If, for any reason, your stream might block, then ready
will return false
.
Instead, try reading your files like this:
String line = reader.readLine();
while (line != null) {
// code code code
line = reader.readLine();
}
这篇关于(reader.ready())和使用for循环读取文件有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!