CJxD CJxD - 3 years ago 310
Java Question

Files.createDirectory() : FileAlreadyExistsException

I have a seemingly strange issue using Java 7's

Files
class.
I want to make sure my directory and files exist before I start writing to avoid a
FileNotFoundException
, and according to the Javadocs,
createDirectory
checks for "the existence of the file and the creation of the directory if it does not exist"

So if it checks first, why do I have a problem with the following code when the directory already exists?

private void writeFile() throws IOException {
// Make sure parent directory and file are ready
File file = "mydirectory/my.file";
File parent = file.getParentFile();
if (parent != null)
Files.createDirectory(parent.toPath()); // Why do I get FileAlreadyExistsException? =[
Files.createFile(file.toPath());

// Do some file writing stuff!
}


I know I could just to a 'if not file exists then create' thing, but I thought the whole point of this method was to take care of all that for me!

Exception data:

java.nio.file.FileAlreadyExistsException: mydirectory
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.createDirectory(Unknown Source)
at java.nio.file.Files.createDirectory(Unknown Source)

Answer Source

From the documentation

public static Path createDirectories(Path dir, FileAttribute<?>... attrs) throws IOException

"Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists."

Maybe you could use that one

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download