2012-03-03 28 views
0

我試圖用我創建的方法讀取整個文本文件。文本文件的所有行按照我的意願打印出來,但打印出來時文件的最後一行顯示爲空。文件中的最後讀取行輸出爲空

private void readFile(String Path) throws IOException{ 
    String text = ""; //String used in the process of reading a file 

    //The file reader 
    BufferedReader input = new BufferedReader(
      new FileReader(Path)); 

    //Creating a new string builder. 
    StringBuilder stringBuilder = new StringBuilder(); 

    while(text != null) 
    { 
     //Read the next line 
     text = input.readLine(); 

     stringBuilder.append(text); //Adds line of text into the String Builder 
     stringBuilder.append(newLine); //Adds a new line using the newLine string 
    } 

    //Sets the text that was created with the stringBuilder 
    SetText(stringBuilder.toString()); 
} 

所有文件被打印出來,100%,因爲他們應該除了在法,說「空」我怎麼會寫代碼,所以這條線不會出現在所有的底部增加了一個額外的行?

回答

1

你的循環退出條件是在錯誤的地方。

while ((text = input.readLine()) != null) { 
    stringBuilder.appendText(text) 
    ... 
4

你可以改變這一點:

while(text != null) 
    { 
     //Read the next line 
     text = input.readLine(); 

     // ... do stuff with text, which might be null now 
    } 

要麼這樣:

while((text = input.readLine()) != null) 
    { 
     // ... do stuff with text 
    } 

或本:

while(true) 
    { 
     //Read the next line 
     text = input.readLine(); 
     if(text == null) 
      break; 

     // ... do stuff with text 
    } 

或本:

text = input.readLine(); 
    while(text != null) 
    { 
     // ... do stuff with text 

     //Read the next line 
     text = input.readLine(); 
    } 

如你所願。

+0

或初始化text = input.readLine();一次在循環之前,並且再次在循環體的末尾。 – jacobm 2012-03-03 18:00:51

+1

@jacobm:的確如此。 。 。但有沒有人真的喜歡這個? – ruakh 2012-03-03 18:07:48

+0

我其實更喜歡它,因爲它最直接地對應於我將如何解釋英語發生了什麼。 (雖然它確實需要你重複兩次相同的行。) – jacobm 2012-03-03 18:16:01

0

使用預讀,你會得到一個清晰的解決方案,這是很容易理解的:

text = input.readLine(); 

while(text != null) 
    { 
     stringBuilder.append(text); //Adds line of text into the String Builder 
     stringBuilder.append(newLine); //Adds a new line using the newLine string 

     //Read the next line 
     text = input.readLine(); 
    } 

使用的預讀的原則,你可以幾乎總是避免不良的退出條件。