Vijay Bhoomireddy
Vijay Bhoomireddy

Reputation: 576

File.mkdirs() doesn't work all the time

I am trying to create a directory using File.mkdirs(). However, it seems to behave strange: sometimes it creates the directory, but other times, it silently ignores the creation of directory.

Earlier I was useing mkdir() but in one of the articles, I read that using mkdirs() would solve the issue. However, it seems not. Any help?

This code is running on a windows machine.

CODE:

File myDir = new File(dirPath);

try{
      myDir.mkdirs();
   } 
   catch(Exception e) {
        e.printStackTrace();
   }

Upvotes: 3

Views: 3762

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

a) You should check mkdirs return value; if false dirs were not created

b) It's better to use 1.7's java.nio.file.Files.createDirectories which will either create all dirs or will throw an exception with explanation why it failed

Upvotes: 5

Jordi Castilla
Jordi Castilla

Reputation: 26961

According to the File API signature of mkdirs() is

public boolean mkdirs()

So you just have to check if the dir has been created...

File myDir = new File(dirPath);

try{
      if (!myDir.mkdirs()) {
          // error here
      }
   } 
   catch(Exception e) {
        e.printStackTrace();
   }

Upvotes: 3

panagdu
panagdu

Reputation: 2133

It is not silently. According to the documentation:

mkdirs returns true if and only if the directory was created; false otherwise

Upvotes: 1

Related Questions