Search code examples
javaprintwriter

Why is the PrintWriter still null after I call the constructor?


I'm trying to write to a file, a simple note to someone who has a book in a library system.

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();

However it's throwing a NullPointerException and as I step through the code with my debugger it says that the PrintWriter is null.

How can the PrintWriter be null? I did not get an Exception creating the PrintWriter.


Solution

  • You've shadowed the variable; from the linked Wikipedia article variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. Comment out the type in the try block.

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

    Edit

    Another way to create your file path is to use the System.getProperty(String) to get the "user.home" like

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

    That way you'll get the currently logged in user's home folder on Windows, Mac and/or Linux.