How do I create Directory/folder?
Once I have tested System.getProperty("user.home");
I have to create a directory (directory name "new folder" ) if and only if new folder does not exist.
How do I create Directory/folder?
Once I have tested System.getProperty("user.home");
I have to create a directory (directory name "new folder" ) if and only if new folder does not exist.
Though this question has been answered. I would like to put something extra, i.e. if there is a file exist with the directory name that you are trying to create than it should prompt an error. For future visitors.
Well to create Directory/folder in java we have two methods
Here makedirectory method creates single directory if it does not exist.
And
Here makedirectories method will create all directories that are missing in the path which the file object represent.
For example refer link below (explained very well). Hope it helps!! https://www.flowerbrackets.com/create-directory-java-program/
You can also refer makdir() function for creating a new directory in a folder where you want.
After ~7 year, I will update it to better approach which is suggested by Bozho.
Deprecated:
Just wanted to point out to everyone calling
File.mkdir()
orFile.mkdirs()
to be careful theFile
object is a directory and not a file. For example if you callmkdirs()
for the path/dir1/dir2/file.txt
, it will create a folder with the namefile.txt
which is probably not what you wanted. If you are creating a new file and also want to automatically create parent folders you can do something like this:Here "directory" is the name of the directory you want to create/exist.