Java Reference
In-Depth Information
The path that a Path object encapsulates may or may not reference a real file or directory on your com-
puter. A Path object is fundamental to creating, reading, and writing data files.
You can use a Path object in four basic ways:
• You can analyze or compare Path objects without involving your physical file system; you are
simply comparing or analyzing the path specifications in abstract.
• You can access the physical file system to determine whether a file or directory exists.
• You can access the physical file system to create a physical file or directory.
• You can access a file in the physical file system to read it or write it.
I discuss the first three possibilities in this chapter. You find out about reading and writing files in subse-
quent chapters. Let's look at how you create a Path object corresponding to a given path.
You can also create a Path object using the static get() method that is defined in the
java.nio.file.Paths class. The Paths class is a helper class that defines two versions of the get() meth-
od. One creates a Path object from a string that you supply as the argument specifying the path; the other
creates a Path object from a java.net.URI object. The URI class encapsulates a uniform resource identifi-
er , commonly known as a URI . A URI is used to reference a resource on the World Wide Web and the most
common form of URI is a URL — a uniform resource locator .
Here's how you might create a Path object from a String object:
Path myPath = Paths.get(
"C: /Program Files (x86)/Java /jdk1.7.0/src/java/nio/file");
This creates a Path object encapsulating the same path as you created with the getPath() method. The
get() method is the equivalent of calling the getPath() method for the default FileSystem object. As with
the getPath() method, the Paths.get() method accepts a series of string arguments specifying the path.
To specify a path to a physical file, you just need to make sure that the string refers to a file and not a
directory. For example:
Path myFile = Paths.get(
"C: /Program Files (x86)/Java /jdk1.7.0/src/java/nio/file/Path.java");
This statement sets the object myFile to the path that corresponds to the source file that contains the
definition of the Path interface.
NOTE A Path object only encapsulates the path to a file, not the file itself. You see later in
this chapter how you use a path object to access a physical file.
The other get() method in the Paths class enables you to define a Path object from an object of type
URI. The URI class provides several constructors for creating URI objects, but getting into the detail of these
is too much of a diversion from our present topic.
Absolute and Relative Paths
Search WWH ::




Custom Search