gpt4 book ai didi

java - 文件中最后读取的行打印为空

转载 作者:行者123 更新时间:2023-12-01 17:32:35 25 4
gpt4 key购买 nike

我正在尝试使用我创建的方法读取整个文本文件。文本文件的所有行都按照我想要的方式打印出来,但是文件的最后一行在打印时显示为空。

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”之外,我将如何编写代码以使该行根本不会出现?

最佳答案

您可以更改此设置:

    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();
}

随你喜好。

关于java - 文件中最后读取的行打印为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9548401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com