Files.createDirectory (): FileAlreadyExistsException

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) 
+6
source share
3 answers

From the documentation

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

"Creates a directory, first creating all non-existent parent directories. Unlike the createDirectory method, an exception is not thrown if the directory cannot be created because it already exists.

Perhaps you could use this

+15
source

Files.createDirectory actually creates a directory β†’ "Creates a new directory .... The createDirectories method should be used where you want to first create all non-existent parent directories."

If you want to make sure the file exists, just use the file.exists () method

+1
source

The Java 7 documentation already mentions that you will get a FileAlreadyExistsException . So what is the problem?

0
source

Source: https://habr.com/ru/post/943480/


All Articles