How to create directory in java

In this post we are going to learn how to create directory in java.

how to create directory in java

To create directory in java we need two methods mkdir() and mkdirs() of File class of java.io.File Standard java IO package which returns boolean value.

mkdir() method create single directory.

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

Also read – java list directory

Now let’s see an example,

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() method creates directory and its sub-directories together.

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

Also read – java rename file

Here’s the example,

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.


Java NIO

In java 7 we can create 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();
}
}
}
}