Create Directory in Java

 Posted On  | Yashwant Chavan 

In this tutorial we will learn how to create directory in Java. Use File mkdir() and mkdirs() methods to create directory and multiple directories with path names. As both methods mkdir() and mkdirs() return a boolean value indicating whether the directories are successfully created or not.

File.mkdir() syntax

The java.io.File.mkdir() creates directory named by this abstract pathname.

public boolean mkdir(); 

Returns : true if and only if the directory was created; false otherwise

Throws : SecurityException - If a security manager exists and its java.lang.SecurityManager.checkWrite(java.lang.String) method does not permit the named directory to be created.

File.mkdirs() syntax

The java.io.File.mkdirs() creates the directory named by this abstract pathname, including any necessary but non-existent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

public boolean mkdirs(); 

Returns : true if and only if the directory was created, along with all necessary parent directories; false otherwise

Throws : SecurityException - If a security manager exists and its java.lang.SecurityManager.checkWrite(java.lang.String) method does not permit verification of the existence of the named directory and all necessary parent directories.

Create Directory Example

The following example demonstrates how to create directory using java.io.File.mkdir()

package com.technicalkeeda.app;

import java.io.File;

public class CreateDirectoryExample {

    public static void main(String[] args) {

        File directory = new File("C:\\demo");

        boolean status = directory.mkdir();

        if (status) {
            System.out.println("Directory is created!!!");
        } else {
            System.out.println("Sorry unable to create directory!!!");
        }

        File directories = new File("C:\\images\\img\\logos");

        status = directories.mkdirs();

        if (status) {
            System.out.println("Multiple directories are created!!!");
        } else {
            System.out.println("Sorry unable to create directories!!!");
        }

    }

}

output

Directory is created!!!
Multiple directories are created!!!


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0334 seconds.