user364669
user364669

Reputation: 591

How to create a folder in Java?

How can I create an empty folder in Java?

Upvotes: 58

Views: 23702

Answers (8)

Andy White
Andy White

Reputation: 88475

Use the mkdir method on the File class:

https://docs.oracle.com/javase/1.5.0/docs/api/java/io/File.html#mkdir%28%29

Upvotes: 5

Ripon Al Wasim
Ripon Al Wasim

Reputation: 37826

The following code would be helpful for the creation of single or multiple directories:

import java.io.File;

public class CreateSingleOrMultipleDirectory{
    public static void main(String[] args) {
//To create single directory
        File file = new File("D:\\Test");
        if (!file.exists()) {
            if (file.mkdir()) {
                System.out.println("Folder/Directory is created successfully");
            } else {
                System.out.println("Directory/Folder creation failed!!!");
            }
        }
//To create multiple directories
        File files = new File("D:\\Test1\\Test2\\Test3");
        if (!files.exists()) {
            if (files.mkdirs()) {
                System.out.println("Multiple directories are created successfully");
            } else {
                System.out.println("Failed to create multiple directories!!!");
            }
        }
    }
}

Upvotes: 0

Toukea Tatsi
Toukea Tatsi

Reputation: 199

Better to use mkdirs as:

new File("dirPath/").mkdirs();

mkdirs: also create parent directories if these do not exist.

ps: don't forget the ending / that shows explicitly you want to make a directory.

Upvotes: 0

Wendel
Wendel

Reputation: 2977

Using Java 8:

Files.createDirectories(Paths.get("/path/to/folder"));

Same:

new File("/path/to/folder").mkdirs();

Or

Files.createDirectory(Paths.get("/path/to/folder"));

Same:

new File("/path/to/folder").mkdir();

Upvotes: 4

micha
micha

Reputation: 49612

With Java 7 and newer you can use the static Files.createDirectory() method of the java.nio.file.Files class along with Paths.get.

Files.createDirectory(Paths.get("/path/to/folder"));

The method Files.createDirectories() also creates parent directories if these do not exist.

Upvotes: 20

Luc M
Luc M

Reputation: 17334

File f = new File("C:\\TEST");
try{
    if(f.mkdir()) { 
        System.out.println("Directory Created");
    } else {
        System.out.println("Directory is not created");
    }
} catch(Exception e){
    e.printStackTrace();
} 

Upvotes: 77

SLaks
SLaks

Reputation: 888233

Call File.mkdir, like this:

new File(path).mkdir();

Upvotes: 21

Matt
Matt

Reputation: 44078

Use mkdir():

new File('/path/to/folder').mkdir();

Upvotes: 6

Related Questions