gpt4 book ai didi

Java BufferedReader.readLine() 读取文件时返回 null

转载 作者:行者123 更新时间:2023-12-01 18:18:33 24 4
gpt4 key购买 nike

我需要一些帮助。这是我的功能:

public String[] getLines(String filename) {
String[] returnVal = null;
int i = 0;

try {
BufferedReader br = new BufferedReader(new FileReader(new File(filename)));

for(String line; (line = br.readLine()) != null; ) {
// process the line.
returnVal[i] = line;
i++;
}

br.close();
}
// Catches any error conditions
catch (Exception e)
{
debug.error("Unable to read file '"+filename+"'");
debug.message(e.toString());
}

return returnVal;
}

它应该返回 String[] 数组,其中包含指定文件中的所有行。但我只得到异常作为返回:

java.lang.NullPointerException

当我尝试打印结果时,结果为空。有任何想法吗?谢谢!

最佳答案

您明确将该值设置为 null:

String[] returnVal = null;

由于您不知道它将包含多少个元素,因此应该使用 ArrayList相反*:

ArrayList<String> returnVal = new ArrayList<>();

* 请参阅 API 以了解应使用哪些方法向其中添加对象

关于Java BufferedReader.readLine() 读取文件时返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28279503/

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