1

Directories some_folder, some_folder_1, some_folder_2, and some_folder_3 don't exist initially.

File folder1 = new File("some_folder/some_folder_1"); 
File folder2 = new File("some_folder/some_folder_2"); 
File folder3 = new File("some_folder/some_folder_3"); 

if(!folder1.exists()) {
    folder1.mkdirs();
}

if(!folder2.exists()) {
    folder2.mkdirs();
}

if(!folder3.exists()) {
    folder3.mkdirs();
}

Would that be a good way to do this?

1
  • You may also want to check the return value of mkdirs() to ensure that the directory has been created. Commented Jun 25, 2009 at 17:58

3 Answers 3

6

Don't use the path separator, use the correct constructor instead:

File folder1 = new File("some_folder", "some_folder_1"); 
if (!folder1.exists()) {
    folder1.mkdirs(); // returns a boolean
}
Sign up to request clarification or add additional context in comments.

Comments

6

Well you don't need the tests - mkdirs just returns false if the directory already exists. I'd prefer to use one "base" file for some_folder to avoid hard-coding the slash, even though a forward slash is likely to work on most popular platforms :)

File baseFolder = new File("some_folder");
new File(baseFolder, "some_folder_1").mkdirs();
new File(baseFolder, "some_folder_2").mkdirs();
new File(baseFolder, "some_folder_3").mkdirs();

Note that this won't throw any exceptions if the names already exist but as files instead of folders...

2 Comments

To add to this, if you have more than 2 or 3 folders, you might want to consider loops and collections
Agreed (as per Carl's answer - except preferably with braces :)
1

or

String[] folders = {"some_folder_1", "some_folder_2", "some_folder_3"};
File root = new File("some_folder");
for (String folder: folders)
    new File(root, folder).mkdirs();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.