Java - File mkdir() Method



.

Description

The Java File mkdir() creates the directory named by this abstract pathname.

Declaration

Following is the declaration for java.io.File.mkdir() method −

public boolean mkdir()

Parameters

NA

Return Value

The method returns true if the directory is created, else the method returns false.

Exception

SecurityException − If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method denies access to create the named directory.

Example 1

The following example shows the usage of Java File mkdir() method. We've created a File reference. Then we're creating a File Object using a directory path which is present in the given location. Using mkdir() method, we're trying to create the folder and getting the result in boolean variable. Then we're printing the status of directory being created or not.

package com.tutorialspoint;
import java.io.File;
public class FileDemo {
   public static void main(String[] args) {      
      File f = null;
      boolean bool = false;      
      try {
         f = new File("F:/Test2");
         
         // create the directory
         bool = f.mkdir();
         
         // print
         System.out.print("Directory created? "+bool);
         
      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result − assuming that we're having a test.txt file at the current location and is not writable.

Directory created? false

Example 2

The following example shows the usage of Java File mkdir() method. We've created a File reference. Then we're creating a File Object using a directory path which is not present in the given location. Using mkdir() method, we're trying to create the folder and getting the result in boolean variable. Then we're printing the status of directory being created or not.

package com.tutorialspoint;
import java.io.File;
public class FileDemo {
   public static void main(String[] args) {      
      File f = null;
      boolean bool = false;      
      try {
         f = new File("F:/Test3");
         
         // create the directory
         bool = f.mkdir();
         
         // print
         System.out.print("Directory created? "+bool);
         
      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result − assuming that we're having a test.txt file at the current location and is not writable.

Directory created? true
java_file_class.htm
Advertisements