The following snippet checks if a given directory exists or not. If it does not it, then creates it. It also creates any non existent directories in the path. The magic is performed by the java.io.File mkdirs() method.
<!--break-->
package com.livrona.snippets.io;
import java.io.File;
/**
* This snippet shows how to recursively create intermediate directories given a
* directory path that needs to be created.
*
* @author mvohra
*
*/
publicclass RecursiveDirectoryCreator {
publicstaticvoid main(String args[]) {
// Nested Directory to be create
String dir ="c:\\a1\\b2\\c3\\d4\\e5"; // windows path
// String dir = "/tmp/a1/a2/a3/a4/a5"; // unix path
// create the file pointer
File file =new File(dir);
// check if directory already exists or not
if (file.exists()) {
System.out.println("Directory : "+ dir +" already exists");
} else {
// create the non existent directory if any
// It returns a boolean indicating whether the operation
// was successful of not
boolean retval = file.mkdirs();
// evaluate the result
if (retval) {
System.out.println("Directory : "+ dir
+" created succesfully");
} else {
System.out.println("Directory : "+ dir +" creation failed");
}
}
}
}