Issue
I am currently working on a method that will create files and directories. Bellow is the use case & problem explained.
1) When a user specifies a path e.g "/parent/sub folder/file.txt", the system should be able to create the directory along with the file.txt. (This one works)
2) When a user specifies a path e.g "/parent/sub-folder/" or "/parent/sub-folder", the system should be able to create all directories. (Does not work), Instead of it creating the "/sub-folder/" or /sub-folder" as a folder, it will create a file named "sub-folder".
Here is the code I have
Path path = Paths.get(rootDir+"test/hello/");
try {
Files.createDirectories(path.getParent());
if (!Files.isDirectory(path)) {
Files.createFile(path);
} else {
Files.createDirectory(path);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
Solution
You need to use createDirectories(Path)
instead of createDirectory(path)
. As explained in the tutorial:
To create a directory several levels deep when one or more of the parent directories might not yet exist, you can use the convenience method, createDirectories(Path, FileAttribute). As with the createDirectory(Path, FileAttribute) method, you can specify an optional set of initial file attributes. The following code snippet uses default attributes:
Files.createDirectories(Paths.get("foo/bar/test"));
The directories are created, as needed, from the top down. In the foo/bar/test example, if the foo directory does not exist, it is created. Next, the bar directory is created, if needed, and, finally, the test directory is created.
It is possible for this method to fail after creating some, but not all, of the parent directories.
Answered By - user1803551
Answer Checked By - David Goodson (JavaFixing Volunteer)