-5

I am trying to write a test file that will overwrite the file I am working on so I can use it with a much more complex program. I keep getting an error message associated with creating a new PrintWriter.

This is the error message:

unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown PrintWriter printWriter = new PrintWriter(file);

This is my code:

import java.io.PrintWriter;
import java.io.File;


public class rewriting_test_file { 

    public static void main(String[] args) {

        File file = new File ("C:/Users/XXXXXXX/Desktop/Java practice/rewriting_test_file.java");
        file.getParentFile().mkdirs();
        PrintWriter printWriter = new PrintWriter(file);
        printWriter.println ("hello");
        printWriter.close ();      
    }
}
sidgate
  • 14,650
  • 11
  • 68
  • 119
  • If you are using an IDE the compiler should give you an `Unhandled exception type FileNotFoundException` on your statement `PrintWriter printWriter = new PrintWriter(file);` to add a `throws` declaration or surround it with a `try/catch` block. – Hemang Dec 30 '15 at 05:49

2 Answers2

1

As the error says, you need to throw the Exception or catch it in try/catch block. Take a look at Exception handling tutorial

public static void main(String[] args) throws IOException
    {

    File file = new File ("C:/Users/XXXXXXX/Desktop/Java practice/rewriting_test_file.java");
    file.getParentFile().mkdirs();
    PrintWriter printWriter = new PrintWriter(file);
    printWriter.println ("hello");
    printWriter.close ();      
        }
    }

or

public static void main(String[] args) 
    {
     PrintWriter printWriter = null;
   try{
      File file = new File ("C:/Users/XXXXXXX/Desktop/Java practice/rewriting_test_file.java");
      file.getParentFile().mkdirs();
      printWriter = new PrintWriter(file);
      printWriter.println ("hello");

        }
       catch(IOException e){
          e.printStackTrace();
       }
       finally{
           if(printWriter!=null)
             printWriter.close ();   //always close the resources in finally block
       }
      }
    }
sidgate
  • 14,650
  • 11
  • 68
  • 119
0

The error message says it all.

Creating a PrintWriter might throw a FileNotFoundException if the file you give it doesn't exist.

You have to wrap it in a try/catch block:

try{
    PrintWriter pw = new PrintWriter(file);
    //do more stuff
}catch(FileNotFoundException e){
    System.out.println("File doesn't exist. Here's the stack trace:");
    e.printStackTrace();
}

Alternatively, declare that your method throws an exception:

public static void main(String[] args) throws IOException { //...
Arc676
  • 4,445
  • 3
  • 28
  • 44