2012-04-22 85 views
1

我有一個從文件讀取內容並將其打印在屏幕上的程序。但程序打印每隔一行,即跳過其他所有行。 package InputOutput;讀取文件內容並寫入控制檯

import java.io.*; 

public class CharacterFileReaderAndFileWriter{ 

    private BufferedReader br = null; 

    private PrintWriter pw = new PrintWriter(System.out, true); 


    /* Read from file and print to console */ 
    public void readFromFile() throws IOException{ 

     try{ 
      br = new BufferedReader(new FileReader("E:\\Programming\\Class files\\practice\\src\\InputOutput\\test.txt")); 
     } 
     catch(FileNotFoundException ex){ 
      ex.printStackTrace(); 
     } 

     String s = null; 
     do{ 
      s = br.readLine(); 
      pw.println(s); 
     } 
     while((s = br.readLine())!=null); 

     br.close(); 
    } 

    /* Main method */ 
    public static void main(String[] args) throws IOException{ 

     CharacterFileReaderAndFileWriter cfr = new CharacterFileReaderAndFileWriter(); 

     cfr.readFromFile(); 
    } 

} 
+5

通知打印線一個在那裏你調用'br.readLine()'和你每次的結果做什麼。 – geekosaur 2012-04-22 02:52:18

回答

6

你爲什麼要這麼做s=br.readline()兩次..你可以把它像這樣。

String s = null; 
while((s = br.readLine())!=null) 
{ 
    pw.println(s); 
} 

readline()每當你打電話給它讀一行,然後轉到下一行。所以當你調用它兩次時,顯然你正在跳過一條線。使用這個代碼,它會工作。

0

刪除你的第一行循環。你正在調用readLine()兩次。

即:

String s = null; 
while((s = br.readLine())!=null) { 
    pw.println(s); 
} 
1

你循環是錯誤的:

String s = null; 
do{ 
    s = br.readLine(); 
    pw.println(s); 
} 
while((s = br.readLine())!=null); 

應該是:

String s = null; 
while((s = br.readLine())!=null) { 
    pw.println(s); 
}; 
+0

我不認爲你的意思是在你的第二個片段中留下額外的分號...... – 2012-04-22 02:55:02

1

反向您do/while環路避免調用readline兩次,並丟棄所有其它結果:

String s = null; 
while((s = br.readLine())!=null) { 
    pw.println(s); 
} 
0

您需要如果你想和do一起去修改你的do-while循環,那麼很好代碼如下。

String s = null; 
do{   
    pw.println(s); 
} 
while((s = br.readLine())!=null); 

br.close(); 
0

變化是:

for(String s; (s = br.readLine()) != null;) { 
     pw.println(s); 
    } 
0

您使用br.readLine()兩次。

String s = null; 
    do{ 
     s = br.readLine(); //here it read first line 
     pw.println(s);  //here it prints first line  
    } 
    while((s = br.readLine())!=null); //here s read second line 
             //note that it is not printing that line 

String s = null; 
    do{ 
     s = br.readLine(); //this time it read third line 
     pw.println(s);  //now it prints third line 
    } 
    while((s = br.readLine())!=null); // this time it reads fourth line 

因此,這一進程將繼續下去,你的程序將陸續