gpt4 book ai didi

java - 打印未找到文件的 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 14:43:29 25 4
gpt4 key购买 nike

如果找不到文件,如何打印NullPointerException?我想使用 JOptionPane 显示一条消息,但它不起作用。

我尝试了以下方法:

public void readTextFile()  {
FileInputStream fs = null;

try {
URL file2 = getClass().getResource("/ReadWriteFile/Student.txt");
String file_path=file2.getPath();
file_path=file_path.replaceFirst("/","");
File file = new File(file_path);
fs = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fs));

try {
String line = reader.readLine();

while(line != null){
System.out.println("line=="+line);
line = reader.readLine();
}
}

catch (IOException e) {
e.printStackTrace();
}
}

catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null,"The file you trying to reach is not found");
Logger.getLogger(Read_WriteToFile.class.getName()).log(Level.SEVERE, null, ex);
}
}

最佳答案

try {

...

} catch (Exception e) {
e.printStackTrace();

}

它将打印所有异常,包括 RunTimeException ,例如 NullPointerException

关于java - 打印未找到文件的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15703074/

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