How to create folder in Java

2 ways of creating a folder in Java


A tiny and easy example to create a directories in Java with mkdir() and mkdirs() methods.


import java.io.File;
class CreateDirectory
{
public static void main(String args[])
{
// Create a java.io.File object, specify the name of the folder
File f=new File("mydir");

// Create directory with specified name, true is returned if created.
boolean flag=f.mkdir();

// Print whether true/false
System.out.println("Directory created (T/F)? "+flag);
}
}

------------------------------------
Output
------------------------------------
Directory created (T/F)? true

Creating directories & sub directories


For creating directories along with sub directories, you must use mkdirs() method because mkdir() has the capability to create only one dir which does not contain any sub directories. The following example gives you a better understand.

import java.io.File;
class CreateDirs
{
public static void main(String args[])
{
// Create a file object for the following path (all are dirs)
File f=new File("mydir\\subdir\\sub-sub dir");

// Create directories, mydir > subdir > sub-sub dir. True is returned when dirs are created.
boolean flag=f.mkdirs();

// Print true/false
System.out.println("Are dirs created (T/F)? "+flag);

}
}

-------------------------------
Output
-------------------------------
Are dirs created (T/F)? true

No comments: