15

I'm trying to create a simple program that will output a string to a text file. Using code I found here, I have put together the following code:

import java.io.*;

public class Testing {

  public static void main(String[] args) {

    File file = new File ("file.txt");
    file.getParentFile().mkdirs();

    PrintWriter printWriter = new PrintWriter(file);
    printWriter.println ("hello");
    printWriter.close();       
  }
} 

J-grasp throws me the following error:

 ----jGRASP exec: javac -g Testing.java

Testing.java:10: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
    PrintWriter printWriter = new PrintWriter(file);
                              ^
1 error

 ----jGRASP wedge2: exit code for process is 1.

Since I'm pretty new to Java, I have no idea what this means. Can anybody point me in the right direction?

3
  • 1
    Search the internet for java exception tutorial and work through one of the tutorials you find. Nov 5, 2013 at 12:28
  • 1
    For starters, and simple one-off programs, add the throws FileNotFoundException (or, to be more general, throws IOException) to the main header line, as Black Panther suggests. As you get more sophisticated you'll want to use try/catch handlers, but one step at a time.
    – Hot Licks
    Nov 5, 2013 at 12:31
  • +1 for a well-stated question, though you probably could have found an answer if you had searched a little harder.
    – Hot Licks
    Nov 5, 2013 at 12:33

4 Answers 4

15

You are not telling the compiler that there is a chance to throw a FileNotFoundException a FileNotFoundException will be thrown if the file does not exist.

try this

public static void main(String[] args) throws FileNotFoundException {
    File file = new File ("file.txt");
    file.getParentFile().mkdirs();
    try
    {
        PrintWriter printWriter = new PrintWriter(file);
        printWriter.println ("hello");
        printWriter.close();       
    }
    catch (FileNotFoundException ex)  
    {
        // insert code to run when exception occurs
    }
}
1
  • Thanks! Managed to get it up and running :) Nov 5, 2013 at 13:01
3

If you're very new to Java, and just trying to learn how to use PrintWriter, here is some bare-bones code:

import java.io.*;

public class SimpleFile {
    public static void main (String[] args) throws IOException {
        PrintWriter writeMe = new PrintWriter("newFIle.txt");
        writeMe.println("Just writing some text to print to your file ");
        writeMe.close();
    }
}
0
2

a PrintWriter might throw an exception if there is something wrong with the file, like if the file doesn't exist. so you have to add

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

then it will compile and use a try..catch clause to catch and process the exception.

-1

This means that when you call new PrintWriter(file), it can throw an exception when the file you want to write to doesn't exist. So you either need to handle that exception, or make your code re-throw it for the caller to handle.

import java.io.*;

public class Testing {

    /**
     * This writes a string to a file.
     * If an exception occurs, we don't care if nothing gets written.
     */
    public void writeToFileWithoutThrowingExceptions(File file, String text) {
        // Yes, we could use try-with-resources here,
        // but that would muddy the example.
        PrintWriter printWriter;
        try {
            printwriter = new PrintWriter(file);
            printWriter.println(text);
        } catch (FileNotFoundException fnfe) {
            // Do something with that exception to handle it.
            // Since we said we don't care if our text does not get written,
            // we just print the exception and move on.
            // Printing the exception like this is usually a bad idea, since
            // now no-one knows about it. Logging is better, but even better
            // is figuring out what we need to do when that exception occurs.
            System.out.println(fnfe);
        } finally {
            // Whether an exception was thrown or not,
            // we do need to close the printwriter.
            printWriter.close();
        }
    }

    /**
     * This writes a string to a file.
     * If an exception occurs, we re-throw it and let the caller handle it.
     */
    public void writeToFileThrowingExceptions(File file, String text) throws FileNotFoundException {
        // We use try-with-resources here. This takes care of closing
        // the PrintWriter, even if an exception occurs.
        try (PrintWriter printWriter = new PrintWriter(file)) {
            printWriter.println(text);
        }
    }
    
    public static void main(String[] args) {
        File file = new File("file.txt");
        file.getParentFile().mkdirs();

        // We call the method that doesn't throw an exception
        writeToFileWithoutThrowingExceptions(file, "Hello");
        
        // Then we call the method that _can_ throw an exception
        try {
            writeToFileThrowingExceptions(file, "World");
        } catch (FileNotFoundException fnfe) {
            // Since this method can throw an exception, we need to handle it.
            // Note that now we have different options for handling it, since             
            // we are now letting the caller handle it.
            // The caller could decide to try and create another file, send
            // an e-mail, or just log it and move on.
            // Again, as an example, we just print the exception, but as we
            // discussed, that is not the best way of handling one.
            System.out.println(fnfe);
        }
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.