【问题标题】:Why bufferedreader.readLine() needs to equal to a temporary string while reading it?为什么 bufferedreader.readLine() 在读取时需要等于一个临时字符串?
【发布时间】:2017-07-07 02:21:08
【问题描述】:

如下面的代码 sn-p 所示。使用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())

【问题讨论】:

  • 你当然可以这样做,那你为什么不试试呢?你很快就会明白为什么你不应该。
  • 每次调用readLine 都会将内部指针移到下一行。该循环将跳过文件的每一行。
  • 因为每次调用readLine()都会返回不同的值。
  • 按照 Javadocs 读取一行文本。 调用两次 == 读取两行文本
  • 因为您需要临时字符串,因为那是 readLine() 结果所在的位置。否则你就把它扔掉。

标签: java bufferedreader java-io


【解决方案1】:

如果你这样做

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

您将丢弃每隔一行。想想看。每次在循环中执行readLine() 并测试它是否不是null。好的,它不是,所以你进入循环并执行 another readLine()。您阅读和测试以确定是否应该进入循环的那行发生了什么?

【讨论】:

  • 谢谢!我现在明白了!
  • @Johnny:别忘了accept 回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-18
相关资源
最近更新 更多