Java Reference
In-Depth Information
All of the preceding operations involve just the information encapsulated by the Path object. The file or
directory itself is not queried and may or may not exist.
You can compare a given Path object path1 for equality with another Path object, path2 , using the
equals() method:
if(path1.equals(path2) {
// Paths are equal...
}
Equality is system dependent and comparisons may or may not be case sensitive. The equals() method
for a Path object simply compares the paths without checking whether the path's reference a real file or
directory.
To convert a relative path to an absolute path you call its toAbsolutePath() method:
Path absolutePath = path.toAbsolutePath();
If the Path object is already an absolute path, the method returns a reference to the same object.
Querying Files and Directories
The java.nio.file.Files class defines static methods that provide a wide range of operations with paths,
files and directories. Let's look at a few of the most interesting methods. You can use the Files class meth-
ods in Table 9-3 to examine the file or directory that is identified by a Path object.
TABLE 9-3 : File Class Methods that Examine Files and Directories
METHOD
DESCRIPTION
Returns true if the file or directory referred to by path exists and false otherwise. You can specify a
second argument that is a value from the java.nio.file.LinkOption type to specify how symbolic
links are to be handled. The default is NOFOLLOW_LINKS so links are not followed.
exists( Path
path)
Returns true if the file or directory referred to by path does not exist and false otherwise. There is an
optional second argument that is the same as with the exists() method.
notExists(
Path path)
Returns true if path refers to a file that is hidden and false otherwise. How a file is hidden is system
dependent. Under UNIX a hidden file has a name that begins with a period. Under Windows a file is
hidden if it is marked as such within the file system.
isHidden(
Path path)
Returns true if path1 references the same file as path2 . If path1 and path2 are equal Path objects,
this method does not check whether the file exists. The method can throw an IOException if an I/O er-
ror occurs.
isSameFile(
Path path1,
Path path2)
NOTE All operations that access the file system on the local machine can throw an exception
of type SecurityException if access is not authorized — in an applet, for example. This is
the case with all of the methods here. However, for an exception of type SecurityException
tobethrown,asecuritymanagermustexistonthelocalmachine,butbydefaultaJavaapplic-
ation has no security manager. An applet, on the other hand, always has a security manager
by default. A detailed discussion of Java security is beyond the scope of this topic.
 
 
Search WWH ::




Custom Search