Java Reference
In-Depth Information
}
static void createSingleDirectory(Path path) {
try {
Files.createDirectory(path);
path = path.toAbsolutePath();
System.out.println("\n" + path + " directory created.");
} catch(NoSuchFileException e) {
System.err.println("\nDirectory creation failed:\n" + e);
} catch(FileAlreadyExistsException e) {
System.err.println("\nDirectory creation failed:\n" + e);
} catch(IOException e) {
System.err.println("\nDirectory creation failed:\n" + e);
}
}
static void createMultipleDirectories(Path path) {
try {
Files.createDirectories(path);
path = path.toAbsolutePath();
System.out.println("\n" + path + " directory created.");
} catch(IOException e) {
System.err.println("\nDirectory creation failed:\n" + e);
}
}
CreatingDirectories.java
You should get the following output as long as the directories created in the example do not exist before
the program executes:
junkDir directory created.
D:\Beginning Java SE 7\Projects\CreatingDirectories\classes\junkDir
directory created.
Directory creation failed:
java.nio.file.FileAlreadyExistsException: junkDir
Directory creation failed:
java.nio.file.NoSuchFileException: D:\Garbage\dir1\dir2\dir3
D:\Garbage\dir1\dir2\dir3 directory created.
D:\Garbage\dir1\dir2\dir3 directory created.
Don't forget to delete the directories that were created after you have run the example.
How It Works
The createSingleDirectory() method uses the createDirectory() method from the Files class
with the Path object that is passed to it as the argument to create the new directory. Any of the three
possible I/O exceptions that may be thrown are caught individually. Note that the catch clause for IOEx-
Search WWH ::




Custom Search