[英]Below two different codes gives me two different outputs in Java
See the below two code and let me know why it is printing like that this is java language 参见下面的两个代码,让我知道为什么它像Java语言那样打印
BufferedReader br = new BufferedReader(new FileReader("file path"));
while(br.readLine()!= null) {
System.out.println(br.readLine());
}
br.close();
This code doesn't print complete file content, however if i use below code it prints complete content of file..please explain 此代码不能打印完整的文件内容,但是,如果我使用下面的代码,它将打印文件的完整内容。请解释
BufferedReader br = new BufferedReader(new FileReader("filepath"));
String str;
while((str=br.readLine())!= null) {
System.out.println(str);
}
br.close();
Simple: you read lines twice from the BufferedReader
, by calling br.readLine()
twice in your while
loop. 简单:通过在
while
循环中两次调用br.readLine()
,可以从BufferedReader
读取两次行。 First a line is read in the condition part ( while (br.readLine()!=null)
) and later again to print it ( ...println(br.readLine())
). 首先在条件部分中读取一行(
while (br.readLine()!=null)
),然后再次打印以打印出来( ...println(br.readLine())
)。
A line that is read is gone from the buffer. 读取的行从缓冲区中消失了。
In your second code part, the line is stored to str
in the condition part. 在您的第二个代码部分中,该行存储在条件部分中的
str
中。 That str
is later also used to print the line. 后来该
str
也用于打印行。
您在第一次在while条件中使用br.readLine()
并在System.out.println(br.readLine())
中第二次使用br.readLine()
读取了两次,这就是为什么它总是打印2,4,6,8...
行和在第二个代码中,您只需读取一次,并将其存储在str
变量中并打印str
,这就是为什么要打印整个文件的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.