We can create dir in java either using File.mkdir() or File.mkdirs().
Example: Create Dir in java using File.mkdir()
1 2 3 4 5 6 7 8 9 10 11 12 |
public static void createDir() { File directory = new File("C:\\kscodes"); boolean dirCreated = directory.mkdir(); if (dirCreated) { System.out.println("Directory Created Successfully !!!"); } else { System.out.println("Unable to create Directory"); } } |
File.mkdir is used to create a directory that is given in the path. If we specify “C:\\kscodes\\work” as in the above example, then a directory “work” will be created.
But for the directory “work” to be created , it is necessary that directory kscodes (as given in the example) should be already present.
If the directory “kscodes” is not present then File.mkdir() will return false and will not create any directory.
So to avoid such situations you can use
File.mkdirs() to create Dir in java.
File.mkdirs() will create the entire tree structure till the last directory if it is not present.
Example : Create Dir in java using File.mkdirs()
1 2 3 4 5 6 7 8 9 10 11 |
public static void createMultipleDir() { File directory = new File("C:\\kscodes\\work\\temp"); boolean multipleDirCreated = directory.mkdirs(); if (multipleDirCreated) { System.out.println("All Directories Created Successfully !!!"); } else { System.out.println("Unable to create Directory"); } } |
In this example we need to create folder / directory named “temp“, but if work or kscodes and work both are not present, then File.mkdirs() will create these missing folders and then create temp directory as we had specified.
Please see the documentation of both these methods on Java API