Java Reference
In-Depth Information
Details for path: luci1.txt
Name count: 1
Name at index 0 is luci1.txt
Parent: null, Root: null, File Name: luci1.txt
Absolute Path: false
Comparing Paths
You can compare two
Path
objects for equality based on their textual representation. The
equals()
method tests for
the equality of two
Path
objects by comparing their string forms. Whether the equality test is case-sensitive depends
on the file system. For example, the path comparison for equality is case-insensitive on Windows. The following
snippet of code shows how to compare Windows paths:
Path p1 = Paths.get("C:\\poems\\luci1.txt");
Path p2 = Paths.get("C:\\POEMS\\LUCI1.TXT");
Path p3 = Paths.get("C:\\poems\\..\\poems\\luci1.txt");
boolean b1 = p1.equals(p2); // Returns true on Windows
boolean b2 = p1.equals(p3); // Returns false on Windows
In this snippet of code,
p1.equals(p3)
returns
false
, even though
p1
and
p3
refer to the same file; this is so
because the
equals()
method compares two paths textually without resolving the actual file references.
■
Tip
the
Path.equals()
method does not test a
Path
for existence in the file system.
The
Path
interface implements the
java.lang.Comparable
interface. You can use its
compareTo()
method to
compare it with another
Path
object textually. The
compareTo()
method returns an
int
value, which is 0, less than 0,
or greater than 0, when the two paths are equal, the path is less than the specified path, or the path is greater than the
specified path, respectively. It is useful in sorting multiple paths in the textual order. The file system is not accessed
when paths are compared using the
compareTo()
method. The ordering used by this method to compare two paths is
platform-dependent. The following snippet of code shows examples of using the
compareTo()
method on Windows:
Path p1 = Paths.get("C:\\poems\\luci1.txt");
Path p2 = Paths.get("C:\\POEMS\\Luci1.txt");
Path p3 = Paths.get("C:\\poems\\..\\poems\\luci1.txt");
int v1 = p1.compareTo(p2); // Assigns 0 to v1
int v2 = p1.compareTo(p3); // Assigns 30 to v2
You can use the
endsWith()
and
startsWith()
methods to test if a path ends with and starts with a given path,
respectively. It is important to note that
endsWith()
and
startsWith()
do not test if a path ends and starts with a text,
respectively. They test if a path ends and starts with components of another path, respectively. The following snippet
of code shows some examples of using these methods with paths on Windows:
Path p1 = Paths.get("C:\\poems\\luci1.txt");
Path p2 = Paths.get("luci1.txt");
Path p3 = Paths.get("poems\\luci1.txt");
Path p4 = Paths.get(".txt");