Java Reference
In-Depth Information
the example, the new directory will be created in the current directory because the path is relative. You see
this exception thrown if you execute the code fragment twice. It can throw a
NoSuchFileException
if any
of the parents for the required directory do not exist. The
createDirectory()
method also throws an ex-
ception of type
java.io.IOException
if an I/O error occurs. These exceptions are checked exceptions so
you should call the method from within a
try
block and provide for catching at least the
IOException
ex-
ception; this catches the other exception because it is a subclass of
IOException
.
If the
Path
object refers to an absolute path, the parent path for the new directory must already exist if
the creation is to succeed with the
createDirectory()
method. When you have the possibility that some
elements in the path for a directory that you want to create may not exist, you can call the static
createDir-
ectories()
method that is defined in the
Files
class with the
Path
object as the argument. This creates all
the required directories. Here's an example:
Path path = Paths.get("D:/Garbage/dir/dir1/dir2");
try {
Files.createDirectories(path);
} catch(IOException e) {
e.printStackTrace(System.err);
}
If any of the subdirectories of the final directory
dir2
do not exist, they are created. When you are creat-
ing a new directory that you specify by an absolute path, using the
createDirectories()
method obviates
the need to verify that the parent exists. As well as the
IOException
, this method can throw an exception
of type
FileAlreadyExistsException
if a file already exists with the same path. If the directory already
exists, this exception is not thrown. If the
createDirectories()
method fails for some reason, some of the
parent directories may be created before the failure occurs.
Let's try creating some directories in an example.
TRY IT OUT: Creating Directories
Here's an example that uses both methods for creating directories:
import java.nio.file.*;
import java.io.IOException;
public class CreatingDirectories {
public static void main(String[] args) {
Path relPath = Paths.get("junkDir");
createSingleDirectory(relPath);
// Create directory in current
createSingleDirectory(relPath);
// then try it again...
Path absPath = Paths.get("D:/Garbage/dir1/dir2/dir3");
createSingleDirectory(absPath);
// Try creating as single
directory
createMultipleDirectories(absPath); // Now do it right
createMultipleDirectories(absPath); // then try it again...