我试图用我创建的方法读取整个文本文件。文本文件的所有行都按照我的要求打印出来,但打印出来时文件的最后一行显示为null。
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%打印出来,除非方法在底部添加一条额外的行,表示“null”我将如何编写代码以便这条线不会出现?
答案 0 :(得分: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();
}
根据您的喜好。
答案 1 :(得分:1)
您的循环退出条件位于错误的位置。
while ((text = input.readLine()) != null) {
stringBuilder.appendText(text)
...
答案 2 :(得分: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();
}
使用预读原则,您几乎可以始终避免不良的退出条件。