I have a class that creates a root folder "foo" and subfolders in it:
public class FolderCreator {
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");
}
}
I set the number SUBFOLDERS_COUNT and I want the folders and subfolders to be created with average depth = SUBFOLDERS_COUNT/3.
How can I create folders and subfolders with a given average depth?
I figured out my problem! To solve this task, the following algorithm is suitable:
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class FolderCreator {
private static final int SUBFOLDERS_COUNT = 9;
private static final String BASE_PATH = "test/foo";
public static void main(String[] args) {
List<String> subFolders = createSubFolders(SUBFOLDERS_COUNT, SUBFOLDERS_COUNT/3);
for (String subFolder : subFolders) {
System.out.println(subFolder);
}
}
private static List<String> createSubFolders(int subFoldersCount, int firstLevelFoldersCount) {
List<String> paths = new ArrayList<>();
while (firstLevelFoldersCount != 0) {
String folderName = BASE_PATH;
Random random = new Random();
int max = subFoldersCount - firstLevelFoldersCount + 1;
int depth = firstLevelFoldersCount == 1 ? subFoldersCount : 1 + random.nextInt(max);
firstLevelFoldersCount--;
subFoldersCount -= depth;
for (int i = 0; i < depth; i++) {
int layerNumber = i + 1;
int sequenceNumber = 0;
folderName = folderName + "\\" + layerNumber + "st" + "LayerSubFolder" + sequenceNumber;
while (paths.contains(folderName)) {
sequenceNumber++;
folderName = folderName.substring(0, folderName.length() - 1) + sequenceNumber;
}
paths.add(folderName);
File file = new File(folderName);
file.mkdirs();
}
}
return paths;
}
}
The folder structure will as shown in the picture for example: