我试图用我创建的方法读取整个文本文件。文本文件的所有行都会按照我的意愿打印出来,但文件打印出来时的最后一行在打印出来时显示为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());
}
除了该方法在底部添加了一行额外的"null"外,所有文件都会100%打印出来。我该如何编写代码,使这一行根本不会出现?
您可以更改:
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();
}
根据您的喜好。
您的循环退出条件位于错误的位置。
while ((text = input.readLine()) != null) {
stringBuilder.appendText(text)
...
使用预读,您将获得更清洁的解决方案,这很容易理解:
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();
}
使用预读原理,您几乎总是可以避免糟糕的退出条件。