Create a Directory in Java

Java - Create directories with mkdir

We need a pathname to create directories. We can create it using the method java.io.File.mkdir().
This method requires no parameters and it returns true on the success of the directory creation or false otherwise.

package com.javacodestuffs.file.io; import java.io.File; public class CreateDirectoryExample { public static void main(String[] args) { File dir = new File("/hello/world"); boolean done = dir.mkdir(); if (done) { System.out.println("success..."); } else { System.out.println("fail..."); } } }

Create Multiple Nested Directories

package com.javacodestuffs.file.io; import java.io.File; public class CreateNestedDirectoryExample { private static final File TEMP_DIRECTORY = new File(System.getProperty("java.io.tmpdir")); public static void main(String[] args) { File file = new File(TEMP_DIRECTORY, "hello/bala"); File nestedDirectory = new File(file, "java/world"); boolean done = nestedDirectory.mkdir(); if (done) { System.out.println("success..."); } else { System.out.println("fail..."); } } }

We have another way to Create a Directory

import java.io.File; public class CreateDirectory { public static void main(String[] args) { try { File file = new File("C:\\hello\\"); file.createNewFile(); boolean flag = file.mkdir(); System.out.print("Directory created? " + flag); } catch(Exception ex) { System.out.print("error "+ex.getMessage()+" occured while creating directory."); } } }

Posts related to Create a Directory in Java

Java create directory and file
Create directory java 8
Java code to create folder and subfolders
How to check if a directory exists in java
create a file in java
Which class is used to create a directory in java
Java create a folder in the current directory

In this article, we have seen how to  Create a Directory in Java with examples. All source code in the article can be found in the GitHub repository.