Adding Directories

suggest change

To make a new directory from a File instance you would need to use one of two methods: mkdirs() or mkdir().

Note: createNewFile() creates a file, not a directory. The comments below describe each call on its own, assuming the path does not already exist.

File singleDir = new File("C:/Users/SomeUser/Desktop/A New Folder/");
    
File multiDir = new File("C:/Users/SomeUser/Desktop/A New Folder 2/Another Folder/");

// assume that neither "A New Folder" nor "A New Folder 2" exists

singleDir.createNewFile(); // does not append ".file"; a trailing separator often makes this fail
singleDir.mkdir(); // creates the directory
singleDir.mkdirs(); // creates the directory

multiDir.createNewFile(); // throws an IOException because a parent is missing
multiDir.mkdir(); // returns false because a parent is missing
multiDir.mkdirs(); // creates the directory and any missing parents

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents