2016-11-26 23 views
0

我写了下面的代码读取文件时:差异读取文件时使用可变字符串

package com.test.application; 

import java.io.*; 
import java.io.IOException; 

public class FileRead { 

    public static void main(String[] args) { 
     try{ 
      File file=new File("Hello.txt"); 
      FileReader fileReader=new FileReader(file); 

      BufferedReader reader=new BufferedReader(fileReader); 

      /*String line=null; 
      while((line = reader.readLine())!=null){ 
       System.out.println(line); 
      } */ 

      System.out.println("This is using no string variable!!!"); 
      while(reader.readLine()!=null){ 
       System.out.println(reader.readLine()); 
      } 
      reader.close(); 
     }  
     catch(IOException e){ 

     } 

    } 

} 

我的文本文件是:

What is Lorem Ipsum? 
Lorem Ipsum is simply dummy text of the printing and typesetting 
industry. 
Lorem Ipsum has been the industry's standard dummy text ever since the  
1500s, when an unknown printer took a galley of type and scrambled it  
to make a type specimen book. 
It has survived not only five centuries, but also the leap into 
electronic typesetting, remaining essentially unchanged. 
It was popularised in the 1960s with the release of Letraset sheets 
containing Lorem Ipsum passages, and more recently with desktop 
publishing software like Aldus PageMaker including versions of Lorem 
Ipsum. 

我在这里的问题是,当我使用的是字符串变量从文件中读取,我马上获得文件的所有内容,即:

String line=null; 
while((line = reader.readLine())!=null){ 
    System.out.println(line); 
} 

但是,当我使用下面的代码通过文件读取的片段,跳过的几行,以及整个文件没有被读取。

while(reader.readLine()!=null){ 
    System.out.println(reader.readLine()); 
} 

任何人都可以请解释为什么会发生这种情况。

回答

0

您可以调用.readLine()两次,第一次在while之后,第二次在println之后,只有第二个要输出。

0

在你的第二个剪辑中,你要拨打reader.readLine()两次。每次通话都会“消耗”一条线路,所以您只需每隔一行打印一次。

1

这可能发生,因为在non-string variable的情况下,您拨打readLine()两次,然后打印第二项。每个readLine()调用从文件读取行并将当前位置指针移动到下一行。 我建议你使用中间字符串变量。

+0

谢谢,就是这样,我应该注意到了。 –