Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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).

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata