0

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Asma
  • 137
  • 3
  • 15
  • 5
    Note that `mkdirs` returns `false` if it fails, you may use that value. – Arnaud Jul 17 '17 at 15:06
  • 4
    https://docs.oracle.com/javase/7/docs/api/java/io/File.html#mkdirs() – Compass Jul 17 '17 at 15:07
  • 2
    Possible duplicate of [java regular expression to match file path](https://stackoverflow.com/questions/4489582/java-regular-expression-to-match-file-path) – azro Jul 17 '17 at 15:10
  • Thanks a lot @Berger the return value of `mkdirs` solve my problem :) – Asma Jul 17 '17 at 15:22

1 Answers1

1

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

JajaDrinker
  • 652
  • 6
  • 15