I have a seemingly strange problem using the Java 7 Files class. I want to make sure my directory and files exist before I start writing, to avoid a FileNotFoundException , and according to Javadocs createDirectory checks if a file exists and createDirectory directory if it doesnβt exist "
So, if he 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 that I can simply create "if not a file, and then create", but I thought that the whole point of this method was to take care of all this for me!
Exceptional 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)
source share