O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required