How to create directory in java

Let’s learn how to create directory in java.

how to create directory in java

How to make directory in java

How to create directories in java is most frequently asked java interview question.

There are two methods to create directory. They are mkdir() and mkdirs() of class File, which returns boolean value.

Also read – treeset in java

mkdir() method create single directory.

File directory = new File(“D:\\DirectoryExample”);

Now let’s see file mkdir() method in java example,

import java.io.*;

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




Output:

Directory created


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

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

Here’s the file mkdirs() method in java example,

import java.io.File;

public class CreateDirectoryDemo
{
   public static void main(String[] args)
   {
      File directory = new File("D:\\DirectoryExample\\subdirectory1\\subdirectory2");
      if(!directory.exists()) 
      {
         if(directory.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) in java both return boolean value to show program status.


Java NIO

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