Recipe 11.9 Creating 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, the calls:

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

succeed, whereas:

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

fails, 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 are left in the filesystem.

Notice that 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 on the command-line).



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net