0

I am trying to create a directory in Java. I think I have provided correctly all necessary things so that I make the directory, but it is not created. You can see from my code below and the corresponding output that every element from which I compose the path of the new directory should be correct and valid. It seems, however, that tDir.mkdir(); is not doing anything, and therefore the success variable is always false. I cannot understand why. Thank you in advance.

System.out.println("experimentDir: " + experimentDir);
System.out.println("item.getName(): " + item.getName());
System.out.println("dirName: " + dirName);
String tDirStr = experimentDir + "/" + item.getName() + "All/" 
    + dirName + "DataAll";
System.out.println("tDirStr: " + tDirStr);
File tDir = new File(tDirStr);
if (tDir.exists()) {
      System.out.println("EXISTS!!!");
} else {
      boolean success = tDir.mkdir();
      if(success) {
            System.out.println("Dir created");
      } else {
            System.out.println("No dir created!");
      }

Output:

 experimentDir: /home/Documents/datasets/test-experiments
 item.getName(): PosNegReviews
 dirName: test
 tDirStr: /home/Documents/datasets/test-experiments/PosNegReviewsAll/testDataAll
 No dir created!

3 Answers 3

3

If you want to create multiple (nested) directories you should use mkdirs() (note the s).

Sign up to request clarification or add additional context in comments.

Comments

1

you may be needing to create any parent directory that dont exist. try File.mkdirs().

1 Comment

And double check directory permissions along the path.
0
public class Test1{
    public static void main(String[] args)
    {
        String path="c:\\dir1\\dir2\\dir3\\dir4";
        File dir=new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
    }
}

above code will create dir4 inside C:\dir1\dir2\dir3. If parent folder does not exist, then it will also create.

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.