5

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?

2 Answers 2

4

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");
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's not quite what I wanted. I'll change the question for a better explanation.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.