Recursively create directory

前端 未结 10 589
萌比男神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:45
        // ensures parent directory is created
        File parentFile = destFile.getParentFile();
        if (parentFile != null && !parentFile.exists()) {
            parentFile.mkdirs();
        }
    
        // creates destination file
        if (!destFile.exists()) {
            destFile.createNewFile();
        }
    
    0 讨论(0)
  • 2020-12-30 23:48

    If you don't mind relying on a 3rd party API, the Apache Commons IO package does this directly for you. Take a look at FileUtils.ForceMkdir.

    The Apache license is commercial software development friendly, i.e. it doesn't require you to distribute your source code the way the GPL does. (Which may be a good or a bad thing, depending on your point of view).

    0 讨论(0)
  • 2020-12-30 23:54

    I would write a little utility method that takes the start and the end letter as well as the desired deepth as parameters. This method calls itself recursively till done:

     private static void createAlphabetFolders(File parent, int start, int end, int deepth){
    
        if(deepth <= 0){
          return;
        }
    
        for (int i=start; i < end; i++){
    
          // create the folder
          String folderName = "" + ((char) i);
          File folder = new File(parent, folderName);
          System.out.println("creating: " + folder.getPath());
          folder.mkdirs();
    
          // call recursively
          createAlphabetFolders(folder, start, end, deepth-1);
        }
      }
    

    One would call it like this:

    createAlphabetFolders(new File("abctest"), 'A', 'E', 5);
    
    0 讨论(0)
  • 2020-12-30 23:54

    Scala code:

      def makePathRecursive(path: String) = {
        import java.io.File
        import scala.util.{Try, Failure, Success}
    
        val pathObj = new File(path)
        pathObj.exists match {
          case true => // do nothing
          case false => Try(pathObj.mkdirs) match {
            case Success(_) => // it worked 
            case Failure(e) => // maybe created meanwhile by another thread
              pathObj.exists match { 
              case false => throw new Exception(e)
              case _ =>  
            }
          }
        }
      }
    
    0 讨论(0)
提交回复
热议问题