Create directory java program

Hey guys!! Welcome to flower brackets blog. In this post we are going to learn a classic example of create directory java program.

create directory java program

Two methods mkdir() and mkdirs() of File class is used to create directory which returns boolean value.

mkdir() or Make directory method create single directory.

File directory = new File("D:\\DirectoryExample");

Also read – java list directory

Now let’s see an example on how to create a directory in java,

import java.io.*;

public class CreateDirectory
{
   public static void main(String[] args)
   {
      File directory = new File("D:\\DirectoryExample");
      if(!fl.exists()) 
      {
         if(fl.mkdir()) 
         {
            System.out.println("Directory is created");
         } 
         else 
         {
            System.out.println("Directory not created");
         }
      }
   }
}

Output:

Directory created


mkdirs() or Make directories method in java creates directory and its sub-directories together.

File directory = new File("D:\\DirectoryExample\\subdirectory1\\subdirectory2");

Also read – java rename file

Here’s the code,

import java.io.File;

public class CreateDirectoryDemo
{
   public static void main(String[] args)
   {
      File directory = new File("D:\\DirectoryExample\\subdirectory1\\subdirectory2");
      if(!fl.exists()) 
      {
         if(fl.mkdirs()) 
	 {
            System.out.println("Sub directories created");
         } 
         else
         {
            System.out.println("Sub directories not created");
         }
      }
   }
}

Output:

Sub directories created

NOTE : make directories method(mkdirs) and make directory method(mkdir) both return boolean value to show program status.


Create directory java 7

In java 7 we can create a directory using java nio packages as shown in below example,

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class NioDirectoryExample 
{
   public static void main(String[] args) 
   {
      Path path = Paths.get("D:\\Directory1\\Subdirectory1\\SubSubdirectory2");
      // this will check if directory exists?
      if(!Files.exists(path)) 
      {
         try
         {
            Files.createDirectories(path);
         } 
         catch(IOException ioe) 
         {
            // if create directory fails to execute
            ioe.printStackTrace();
         }
      }
   }
}

Related Posts