Apr 052016

ADM

How to create directory in Java

  • 05 April 2016
  • ADM

 

 

 

How to create directory in Java - images/logos/java.jpg

 

File class from io java.io package provides two methods to create a new folder.

  • mkdir() - Creates the directory named by this abstract pathname.
  • mkdirs() - Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

Example

package com.admfactory.io;

import java.io.File;

public class CreateNewFolder {

    public static void main(String[] args) {

        /** creating a single folder using mkdir */
        String path1 = "c:\\admfactory";
        File f1 = new File(path1);
        System.out.println("Create single folder using mkdir.");
        boolean r1 = f1.mkdir();
        if (r1) {
            System.out.println("'" + path1 + "' created successful.");
        } else {
            System.out.println("'" + path1 + "' new folder failed.");
        }
        System.out.println();

        /** creating a multiple folders using mkdirs */
        String path2 = path1 + "\\f1\\f2\\f3";
        File f2 = new File(path2);
        System.out.println("Create multiple folders using mkdirs.");
        boolean r2 = f2.mkdirs();
        if (r2) {
            System.out.println("'" + path2 + "' created successful.");
        } else {
            System.out.println("'" + path2 + "' new folder failed.");
        }
        System.out.println();

        /** try to create multiple folders using mkdir */
        String path3 = path1 + "\\f4\\f5";
        File f3 = new File(path3);
        System.out.println("Create multiple folders using mkdir.");
        boolean r3 = f3.mkdir();
        if (r3) {
            System.out.println("'" + path3 + "' created successful.");
        } else {
            System.out.println("'" + path3 + "' new folder failed.");
        }

    }
}

Output

Create single folder using mkdir.
'c:\admfactory' created successful.

Create multiple folders using mkdirs.
'c:\admfactory\f1\f2\f3' created successful.

Create multiple folders using mkdir.
'c:\admfactory\f4\f5' new folder failed.

As expected only mkdirs() created multiple folders.

How to create directory in Java - /images/NewFolderJava.png

 

 

 

References