Recursively create directory

前端 未结 10 675
萌比男神i
萌比男神i 2020-12-30 23:20

Does anyone know how to use Java to create sub-directories based on the alphabets (a-z) that is n levels deep?

 /a
    /a
        /a
        /b
        /c
           


        
10条回答
  •  余生分开走
    2020-12-30 23:34

    You could use three loops over characters a-z like so:

    import java.io.*;
    
    public class FileCreate {
    
        public static void main(String[] args) throws Exception {
            char trunkDirectory = 'a';
            char branchDirectory = 'a';
            char leaf = 'a';
    
            while (trunkDirectory != '{') {
                while (branchDirectory != '{') {
                    while (leaf != '{') {
                        System.out.println(trunkDirectory + "/" + branchDirectory + "/" + leaf++);
                    }
                    leaf = 'a';
                    branchDirectory++;
                }
                branchDirectory = 'a';
                trunkDirectory++;
            }
    
        }
    }
    

    This simply outputs the paths to the console. You could use File#mkdirs() to create a recursive directory structure or create the directories in each intermediate part of the nested loop. I'll leave that for you to finish.

提交回复
热议问题