Reputation: 605
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?
Upvotes: 5
Views: 7609
Reputation: 455
We can create a directory or multiple directories Using Path in Simple step:
public static Path createDirectories() throws IOException {
String folderPath = "E://temp/user/UserId/profilePicture";
Path path = Paths.get(folderPath);
return Files.createDirectories(path);
}
Path, Paths and Files classes can be found java.nio.file.*; package which is given below :
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Note :- Make sure method should throws IOException or within try-catch.
Upvotes: 2
Reputation: 18633
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");
}
}
Upvotes: 4