Reputation: 137
I'm working with Java 1.8. I'm trying to create a folder if not exists using this method:
private void createDirIfNotExists(String dirChemin) {
File file = new File(dirChemin);
if (!file.exists()) {
file.mkdirs();
}
}
This works when I give it the right path, for example this creates a folder if it doesn't exist
createDirIfNotExists("F:\\dir")
But when I write an incorrect path (or name), it didn't give me any thing even an error! for example :
createDirIfNotExists("F:\\..?§;>")
So I want to improve my method, so it can create the folder if it doesn't exist by making sure that my path is right, otherwise it should give me an error message.
Upvotes: 0
Views: 664
Reputation: 662
mkdirs()
also creates parent directories in the path this File
represents.
javadocs for mkdirs()
:
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
javadocs for mkdir()
:
Creates the directory named by this abstract pathname.
Example:
File f = new File("non_existing_dir/someDir");
System.out.println(f.mkdir());
System.out.println(f.mkdirs());
will yield false
for the first [and no dir will be created], and true
for the second, and you will have created non_existing_dir/someDir
Upvotes: 1