Adding Directories
suggest changeTo make a new directory from a File instance you would need to use one of two methods: mkdirs() or mkdir().
mkdir()- Creates the directory named by this abstract pathname. (source)mkdirs()- Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories. (source)
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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents