views:

112

answers:

3

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?

+5  A: 

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
}
daveb
+3  A: 

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...

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

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();
Carl Manaster