简体   繁体   English

下面两个不同的代码为我提供了Java中的两个不同的输出

[英]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.

相关问题 为什么我在Java代码中获得两个不同的输出 - Why am I getting two different outputs in Java code 如何在两个不同的输出中识别相同的数字 - How to identify the same number in two different outputs 从Stream获取两个不同的输出 - Getting two different outputs from a Stream 为什么 Java 在两个不同的环境中给我两个不同的错误,即使(简单的)代码是相同的? - Why Java is giving me two different errors in two different envirnonments, even though the (simple) code is the same? Java:将文件保存到两个不同的文件中-请解释我的解决方案 - Java: save file into two different files - please explain me solution 在 Java 中除以两个整数给我 0 还是 100? - Dividing two integers in Java gives me 0 or 100? 以下两个多线程java代码有什么区别? - What is difference between below two multithreaded java codes? Java字符串拆分在Windows和Linux上提供不同的输出 - Java string split gives different outputs on Windows and linux 用Java在日期中添加一个月有两种方式,会产生两种不同的结果(le年哲学?) - Adding a month to a date in Java two ways gives two different results (leap year philosophy?) 相同条件逻辑为Java中的AtomicBooleans生成两个非常不同的字节码。 为什么? - Same condition logic generating two very different byte codes for AtomicBooleans in Java. Why?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM