在调用构造函数后,为什么PrintWriter仍然为null?

时间:2014-12-10 01:07:04

标签: java printwriter

我试图写一个文件,一个简单的笔记给在图书馆系统中有一本书的人。

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?我没有Exception创建PrintWriter

2 个答案:

答案 0 :(得分:3)

shadowed the variable;来自链接的维基百科文章变量阴影发生在某个范围内声明的变量(决策块,方法或内部类)与外部范围中声明的变量同名时。注释掉该类型在try区块。

/* 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上获得当前登录用户的主文件夹。

答案 1 :(得分:0)

如果它在null块中抛出try,则表示文件notifacation.txt不存在。

当然,它会在您声明(或可能重新声明)的try之外抛出异常,并在outFile块内定义try变量尝试块外的SCOPE。

换句话说,outFile块中try的定义已超出范围,无法以任何方式从try块中访问。

请改为:

 PrintWriter outFile = null;
 try {

     outFile = new PrintWriter(filename);
} catch(FileNotFoundException fnfe) {

    // handle exception
}

if(outFile != null)
    outFile.close();// don't forget to close this. Else your data will not be written in the file. But this throws IOException. So handle it too.