I'm trying to create a function that creates multiple folder/subfolders in a single instruction using Java.
I can use File
's mkdirs()
method to create a single folder and its parents.
An example of the struture I want:
folder
└── subfolder
├── subsubfolder1
├── subsubfolder2
└── subsubfolder3
For example in linux I can achieve this with the following command:
mkdir -p folder/subfolder/{subsubfolder1,subsubfolder2,subsubfolder3}
Is there a way I can achieve this in Java?
Not sure if such a method exists, but you can certainly define one:
import java.io.File;
import java.util.Arrays;
class Test {
public static boolean createDirectoriesWithCommonParent(
File parent, String...subs) {
parent.mkdirs();
if (!parent.exists() || !parent.isDirectory()) {
return false;
}
for (String sub : subs) {
File subFile = new File(parent, sub);
subFile.mkdir();
if (!subFile.exists() || !subFile.isDirectory()) {
return false;
}
}
return true;
}
public static void main(String[] args) {
createDirectoriesWithCommonParent(new File("test/foo"), "a", "b", "c");
}
}