gpt4 book ai didi

java - 为什么调用构造函数后 PrintWriter 仍然为 null?

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

我正在尝试写入一个文件,这是给图书馆系统中拥有一本书的人的简单注释。

try {
PrintWriter outFile = new PrintWriter(
"/Users/Test/Desktop/Java/Notifacation.txt");
} catch (FileNotFoundException fnfe) {
System.out.println(fnfe);
}
System.out.println("Book currently loaned out and unavailable to other "
+ "members. Returning to the main menu.");
outFile.println("==========================================================="
+ "=======================================================");
outFile.println("Notifacation for " + b.whoIsCurrentLoaner());
outFile.println("We have received a request for the book currently in your posession; " + b.getTitle());
outFile.println("It would be greatly appreciated if you could return that book as soon as possible when you have finished with it");
outFile.println("==========================================================="
+ "=======================================================");
welcome();
outFile.close();

但是它抛出了 NullPointerException,当我使用调试器单步执行代码时,它说 PrintWriternull

PrintWriter怎么可能是null?我在创建 PrintWriter 时没有遇到 Exception

最佳答案

你已经shadowed the variable ;来自链接的维基百科文章当在某个范围(决策 block 、方法或内部类)中声明的变量与在外部范围中声明的变量具有相同名称时,就会发生变量遮蔽。注释掉类型在 try block 中。

/* PrintWriter */ 
outFile = new PrintWriter("/Users/Test/Desktop/Java/Notifacation.txt");

编辑

创建文件路径的另一种方法是使用 System.getProperty(String)获取“user.home”,例如

 outFile = new PrintWriter(System.getProperty("user.home") 
+ "/Desktop/Java/Notifacation.txt");

这样您就可以在 Windows、Mac 和/或 Linux 上获取当前登录用户的主文件夹。

关于java - 为什么调用构造函数后 PrintWriter 仍然为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27391767/

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