Making New Directories

Problem

You need to create a directory.

Solution

Use java.io.File’s mkdir( ) or mkdirs( ) method.

Discussion

Of the two methods used for creating directories, mkdir( ) creates just one directory while mkdirs( ) creates any parent directories that are needed. For example, if /home/ian exists and is a directory, then the calls:

new File("/home/ian/bin").mkdir(  );
new File("/home/ian/src").mkdir(  );

will succeed, whereas:

new File("/home/ian/once/twice/again").mkdir(  );

will fail, assuming that the directory once does not exist. If you wish to create a whole path of directories, you would tell File to make all the directories at once by using mkdirs( ):

new File("/home/ian/once/twice/again").mkdirs(  );

Both variants of this command return true if they succeed and false if they fail. Notice that it is possible (but not likely) for mkdirs( ) to create some of the directories and then fail; in this case, the newly created directories will be left in the filesystem.

Notice the spelling: mkdir( ) is all lowercase. While this might be said to violate the normal Java naming conventions (which would suggest mkDir( ) as the name), it is the name of the underlying operating system call and command on both Unix and DOS (though DOS allows md as an alias at the command-line level).

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.