问题
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)
回答1:
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
回答2:
Files.createDirectory actually creates the directory -> "Creates a new directory. .... The createDirectories method should be used where it is required to create all nonexistent parent directories first."
If you want to make sure the file exists, just use file.exists() method
回答3:
Java 7 documentation already mentions that you would get a FileAlreadyExistsException
. So what seems to be the problem?
回答4:
if (!Files.isDirectory(Paths.get(dirpath))) {
System.out.println("Output Files parent path does not exist:"+dirpath);
File file = new File(dirpath);
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Output files directory is created!");
} else {
System.out.println("Failed to create output directory!");
}
}
}
first check then create!!
回答5:
I used public static Path createDirectories(Path dir, FileAttribute<?>... attrs) throws IOException
and still got an java.nio.file.FileAlreadyExistsException
because one of the existing files was a symlink. The method is not very reliable.
来源:https://stackoverflow.com/questions/16179102/files-createdirectory-filealreadyexistsexception