gpt4 book ai didi

java - NullPointerException 从文件中读取行

转载 作者:行者123 更新时间:2023-11-30 03:14:14 25 4
gpt4 key购买 nike

我有这个代码:

public static void main(String[] args) {
BufferedReader br = null;

try {
br = new BufferedReader(new FileReader("hello.txt"));

String line;

while ((line = br.readLine().trim()) != null) {
if (line.startsWith("Hello")) {
line = br.readLine().trim();
} else {
... code ...
}
}

br.close();

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

但是一旦文件到达末尾,我就会收到此错误:

Exception in thread "main" java.lang.NullPointerException

上线:

while ((line = br.readLine().trim()) != null) {
为什么?如何解决?

最佳答案

尝试以下操作;您尝试读取的ine为空,因此调用trim会抛出NPE;

while (br.readLine() != null)
{
line = br.readLine().trim()
}

关于java - NullPointerException 从文件中读取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33000771/

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