Java Reference
In-Depth Information
Path sourcePath = Paths.get("D:/Temp1");
try {
Files.move(sourcePath, sourcePath.resolveSibling("Temp2"));
} catch(IOException e) {
System.err.println("I/O error." + e);
}
Renaming a file is essentially the same process. Here's a fragment that creates then renames a directory,
creates a new file in it, and then renames the file:
Path sourcePath = Paths.get("D:/Temp1/Temp2");
try {
Files.createDirectories(sourcePath);
sourcePath = Files.move(sourcePath, sourcePath.resolveSibling("Temp3"));
Path file = sourcePath.resolve("output.txt"); // The path to the file
System.out.println(file);
Files.createFile(file); // Create file in renamed directory
Files.move(file, file.resolveSibling("outputNew.txt")); // Rename the file
} catch(IOException e) {
System.err.println("I/O error." + e);
}
This fragment creates the Temp1 \ Temp2 directory on the D: drive, renames it as Temp1/Temp3 , and then
creates an empty file, output.txt , in it. The new file is then renamed to outputNew.txt .
Copying Files and Directories
The Files class defines a static copy() method that enables you to copy files and directories. When you
use the method to copy a directory that is not empty, only the directory is copied, not the contents. You see
how you can copy a directory and its contents in the next section. The copy() method usage is similar to
that of the move() method. The first argument to the copy() method is a Path object that specifies the item
to be copied and the second argument is a Path object that specifies the copied item in its new location.
There are optional arguments that can be CopyOption references, which are the values REPLACE_EXISTING
and COPY_ATTRIBUTES . These are defined by the java.nio.file.StandardCopyOption enumeration or
the NOFOLLOW_LINKS value that is defined by the java.nio.file.LinkOption enumeration. These options
have the effects on the copy operation shown in Table 9-6 .
TABLE 9-6 : Options for Copy Operations
OPTION EFFECT
REPLACE_EXISTING Causes the target to be replaced if it exists. If the target is a directory, it must be empty for it to be
replaced. A symbolic link is replaced, not the target of the link.
COPY_ATTRIBUTES The attributes of the source file are copied to the target file if possible.
NOFOLLOW_LINKS Symbolic links are not followed. If a symbolic link is being copied, then the link is copied, not the
target of the link.
The copy() method can throw the following exceptions:
UnsupportedOperationException if you specify an option that is not supported.
FileAlreadyExistsException if the target file exists and you have not specified the
REPLACE_EXISTING option.
 
 
Search WWH ::




Custom Search