Create a directory in Java


A directory can be created with the required abstract path name using the method java.io.File.mkdir(). This method requires no parameters and it returns true on the success of the directory creation or false otherwise.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.io.File;
public class Demo {
   public static void main(String[] args) {
      try {
         File file = new File("c:\demo1\");
         file.createNewFile();
         boolean flag = file.mkdir();
         System.out.print("Directory created? " + flag);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

The output of the above program is as follows −

Output

Directory created? false

Note − The output may vary on Online Compilers.

Now let us understand the above program.

The method java.io.File.mkdir() is used to create a directory in Java. Then the boolean value returned by this method is printed. A code snippet that demonstrates this is given as follows −

try {
   File file = new File("c:\demo1\");
   file.createNewFile();
   boolean flag = file.mkdir();
   System.out.print("Directory created? " + flag);
} catch(Exception e) {
   e.printStackTrace();
}

Updated on: 30-Jul-2019

649 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements