Skip to content
Advertisement

how do you create a directory that has 3 other directorys in it and so on

Im trying to create a sort of maze of directorys in java. one directory should have 3 other of it within it and those should also have 3 directory in them up until a certain “deepness level” is reached. I tried something but i couldn’t get it to work properly, it does create 3 folders in one but not inside of the other folders.

my java code:

 private static final int LEVELS = 5;
 private static final int FOLDERS_COUNT = 3;

 int currentLevel = 0;

 public void createFolder(String path) {
     //select random name from a list
     Random r = new Random(); 
     String newFolderName = nameList[r.nextInt(nameList.length)];
     
     //save the new path with the name
     String completePath = path+"/"+newFolderName;
     
     //create folder
     new File(path+"/"+newFolderName).mkdirs();
     
     //increase the deepness level
     currentLevel++;
     
     if(currentLevel <= LEVELS) {
         for(int i = 0; i < FOLDERS_COUNT; i++) // do it again 3 times
             createFolder(completePath);
     }
 }  

I have a bit of trouble expressing myself if i forgot to mention something important please remind me and i will add it.

Advertisement

Answer

if you reach the maximum level return to stop the recursion:

 if(currentLevel > LEVELS + 1) {
    return;
 }

else create a folder. The folder name is the level + index instead of a random name from a list to avoid overwrites due to the same folder name:

else if (currentLevel++ > 1){
    String newFolderName = "level" + (currentLevel - 2) + "_folder" + folderIndex;
    path = path + "/" + newFolderName;
    new File(path).mkdirs();
}

and finally call createFolders recursively:

for(int i = 1; i <= FOLDERS_COUNT; i++)
   createFolders(i, currentLevel, path);
 }

Complete code:

private static final int LEVELS = 5;
private static final int FOLDERS_COUNT = 3;
    
public static void main(String[] args) {
     createFolders(1, 1 , "C:/parentFolder");
}
    
public static void createFolders(int folderIndex, int currentLevel, String path) {
      if(currentLevel > LEVELS + 1) {
        return;
      }else if (currentLevel++ > 1){
        String newFolderName = "level" + (currentLevel - 2) + "_folder" + folderIndex;
        path = path + "/" + newFolderName;
        new File(path).mkdirs();
      }

      for(int i = 1; i <= FOLDERS_COUNT; i++)
         createFolders(i, currentLevel, path);
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement