Java Reference
In-Depth Information
DirectoryNotEmptyException if the target is a directory that exists and is not empty and you
have specified the REPLACE_EXISTING option.
Let's try this out in an example along with some of the other file and directory operations I have dis-
cussed.
TRY IT OUT: Moving and Copying Files and Directories
This example demonstrates creating and deleting directories and copying and moving files. The source
file is MoveAndCopyFiles.java . I'm presenting the code piecemeal as separate methods rather than in
one big block. The example uses static methods for the operations it uses. Here's the MoveAndCopyFiles
class method to create a directory:
static void createSingleDirectory(Path path) {
try {
Files.createDirectories(path);
System.out.println("\n" + path + " directory created.");
} catch(IOException e) {
System.err.println("\nDirectory creation failed:\n" + e);
}
}
MoveAndCopyFiles.java
This method creates a directory from the Path object that is passed to it and outputs a message. Any ex-
ception that is thrown also results in a message.
The next method checks whether a path is a directory:
static boolean isDirectory(Path path) {
try {
BasicFileAttributes attr = Files.readAttributes(
path,
BasicFileAttributes.class);
return attr.isDirectory();
} catch(IOException e) {
System.err.println("I/O error in isDirectory method. " + e);
}
return false;
}
MoveAndCopyFiles.java
The method obtains the attributes for the path by calling the static readAttributes() method that is
defined in the Files class and calls isDirectory() for the BasicFileAttributes object that is re-
turned to test for a directory. The method returns true if the path argument references a directory and
false otherwise.
Search WWH ::




Custom Search