Java PrintWriter to file (on a mac) not working

1.1k views Asked by At

I've read several threads on here and still can't find out why PrintWriter isn't printing to file and is instead throwing a java.io.FileNotFoundException. I've checked the file location, I've checked the upper/lowercases in the file path. Can someone tell me what I'm doing wrong:

    File output = new File("/Users/<myname>/Documents/javaoutput.txt");
    output.getParentFile().mkdir();

    PrintWriter writer = new Printwriter(output);
1

There are 1 answers

0
Kenster On

You're not checking whether the target directory /Users/<myname>/Documents exists or whether the attempt to create it succeeded. new PrintWriter() would throw a FileNotFoundException if the target directory didn't exist.

Something like this might work better:

File output = new File("/Users/<myname>/Documents/javaoutput.txt");
File dir = output.getParentFile();
if (!dir.isDirectory() && !dir.mkdirs()) {
    // handle could not create directory
    throw new SomeException("Could not create target directory '" + dir + "'");
}
PrintWriter writer = new Printwriter(output);

I'm using mkdirs() here instead of mkdir() to create the entire directory path (/Users, /Users/<myname>, and /Users/<myname>/Documents) if necessary. You should decide what your program should do when it couldn't create the directory and add the correct code for that case.