Create Directory using Java

Different ways to create directory in Java.

Using Files Class

You can use Files.createDirectories to create a directory and parent directories that do not exist.

1
2
3
4
5
6
Path path = Paths.get("output/newpath/");
try {
Files.createDirectories(path);
} catch (IOException e) {
e.printStackTrace();
}

Using File Class

java.io.File class provides mkdir() and mkdirs() method to create directory. mkdir() only create a directory. mkdirs() creates directory and all necessary but nonexistent parent directories. Both return true if directory is created.

1
2
3
4
5
6
File file = new File("output/newpath/");
if(file.mkdirs()) {
System.out.println("Directory is created.");
} else {
System.out.println("Fail to create directory.");
}