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

There are two methods to make directory in java. 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 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”);

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 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();
}
}
}
}