为什么bufferedreader.readLine()在读取时需要等于一个临时字符串?



如下面的代码片段所示。使用BufferedReader读取时,Buffereder.readLine()总是设置为临时字符串。

String hello = "hello ";
byte[] data = hello.getBytes();
ByteArrayInputStream bai = new ByteArrayInputStream(data);
try(BufferedReader br = new BufferedReader(new InputStreamReader(bai))){
String temp;
while((temp=br.readLine())!=null)
System.out.println(temp);
}catch(Exception exception){
}

为什么我们不能只做

while(br.readLine()!=null)
System.out.println(br.readLine())

如果你这样做

while(br.readLine()!=null)
System.out.println(br.readLine())

您将丢弃每隔一行。 想想吧。每次循环时,您都会readLine()并进行测试以查看它是否null。 好吧,不是,所以你进入循环并做另一个readLine(). 您阅读和测试以决定是否应该进入循环的行发生了什么变化?

相关内容

最新更新