我試圖用我創建的方法讀取整個文本文件。文本文件的所有行按照我的意願打印出來,但打印出來時文件的最後一行顯示爲空。文件中的最後讀取行輸出爲空
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%,因爲他們應該除了在法,說「空」我怎麼會寫代碼,所以這條線不會出現在所有的底部增加了一個額外的行?
或初始化text = input.readLine();一次在循環之前,並且再次在循環體的末尾。 – jacobm 2012-03-03 18:00:51
@jacobm:的確如此。 。 。但有沒有人真的喜歡這個? – ruakh 2012-03-03 18:07:48
我其實更喜歡它,因爲它最直接地對應於我將如何解釋英語發生了什麼。 (雖然它確實需要你重複兩次相同的行。) – jacobm 2012-03-03 18:16:01