Search code examples
javafileiooutputprintwriter

Getting file not found exception with PrintWriter and File


public static void generateOutput() {
    File file = new File ("C:/Users/me/Desktop/file.txt");
    PrintWriter outputFile = null;
    outputFile = new PrintWriter(file);
}

Above is my code, I am trying to make a PrintWriter that writes to a file I have made on my desktop called file.txt, however I am getting the error "unhandled exception type, file not found exception". I have looked at other posts and I'm unsure why I am still getting this error. I have also tried doing so without the File object. I was hoping for some guidance as to where I went wrong


Solution

  • The most important idea you have to understand here, is that your file may:

    1. not be found;
    2. have its descriptor locked (which means, that some other process uses it);
    3. be corrupted;
    4. be write-protected.

    In all above cases, your Java program, triggering OS Kernel, will crush, and the exception will happen at the runtime. In order to avoid this accident, Java designers decided (and well they did), that PrintWriter should throw (meaning, it is a possibility to throw) FileNotFoundException and this should be a checked exception at compile time. This way developers will avoid more serious run-time problems, like program crush crush.

    Hence, you either have to:

    1. try-catch in your method that PrintWriter; or
    2. throw the exception one level up.

    I think, your question was about why that happens. Here is the answer for both - (1) why? and (2) how to solve it.