Java Reference
In-Depth Information
A second version of the
resolve()
method accepts a
String
argument. This converts the argument to a
Path
object and then works in the same way as the version previously mentioned.
The
relativize()
method is the inverse of the
resolve()
method. It returns a
Path
object that, when
resolved against the current path, results in the
Path
argument. Thus if the current path is
C:\Junk
and the
argument path is
C:\Junk\Temp1\Temp2
then the path
\Temp1\Temp2
is returned.
The
resolveSibling()
method resolves the path supplied as the argument against the parent of the path
for which you call the method. So if you call this method for a
Path
object representing
"C:\junk\file"
with the argument
Path
object representing
"newFile"
, the method returns a
Path
object representing
"C:\junk\newFile"
. An overload of the method accepts an argument of type
String
to specify the path.
This is useful when we get to renaming files later in this chapter.
CREATING AND DELETING DIRECTORIES AND
FILES
When you need to write a new file, you obviously have to be able to create the file initially, and in many
cases, you create a new directory that is to contain the file. I discuss creating directories first and then move
on to file creation.
NOTE
All the directories and files that the examples create in this and subsequent chapters
are on the D: drive or partition. I have coded them like this to avoid adding them to my C:
drive, which is my system drive. If you do not have a drive or partition D: you need to change
the paths in the examples to suit your environment. Take extra care to avoid typos in paths if
they reference your system drive.
Creating Directories
You create a directory by calling the static
createDirectory()
method in the
Files
class with a
Path
ob-
ject that specifies the directory to be created as the argument. This can be an absolute or a relative path. The
new directory is appended to the current directory if the
Path
object is a relative path. Here's how you could
create a new directory in the current directory:
Path path =Paths.get("newDir");
try {
Files.createDirectory(path);
} catch(IOException e) {
e.printStackTrace(System.err);
}
This creates the directory
newDir
in the current directory. The
createDirectory()
method throws an
exception of type
java.nio.FileAlreadyExistsException
if a file or directory exists in the directory in
which you are creating the new directory with the same name as the directory you are trying to create. With