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)
list() returns the array of files and directories in the directory defined by this abstract path name. The method returns null, if the abstract pathname does not denote a directory.
Creating a new directoryThe mkdir() method of this class creates a directory with the path represented by the current object. Instantiate the File class by passing the path of the directory you need to create, as a parameter (String). Invoke the mkdir() method using the above created file object.
The java. nio. file package defines classes to access files and file systems. The API to access file and file system attributes is defined in the java.
In Java, the mkdir() function is used to create a new directory. This method takes the abstract pathname as a parameter and is defined in the Java File class. mkdir() returns true if the directory is created successfully; else, it returns false.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With