Java Reference
In-Depth Information
// Using endsWith()
boolean b1 = p1.endsWith(p2); // Assigns true to b1
boolean b2 = p1.endsWith(p3); // Assigns true to b2
boolean b3 = p1.endsWith(p4); // Assigns false to b3
// Using startsWith()
Path p5 = Paths.get("C:\\");
Path p6 = Paths.get("C:\\poems");
Path p7 = Paths.get("C:\\poem");
boolean b4 = p1.startsWith(p5); // Assigns true to b4
boolean b5 = p1.startsWith(p6); // Assigns true to b5
boolean b6 = p1.startsWith(p7); // Assigns false to b6
The endsWith() method compares the components, not the text, of a path with the specified path. For example,
the path C:\poems\luci1.txt ends with luci1.txt , poems\luci1.txt , and C:\poems\luci1.txt . The same logic is
used by the startsWith() method, though in the reverse order.
You can use the isSameFile(Path p1, Path p2) method of the Files class to check if two paths refer to the
same file. If p1.equals(p2) returns true , this method returns true without verifying the existence of the paths in the
file system. Otherwise, it checks with the file system, if both paths locate the same file. The file system implementation
may require this method to access or open both files. The isSameFile() throws an IOException when an I/O error
occurs.
Listing 10-3 demonstrates how the isSameFile() method works. Let's assume that the file denoted by the path
C:\poems\luci1.txt exists. Since paths p1 and p2 are not equal using the equals() method, the isSameFile()
method looks for these two paths in the file system for existence. It returns true , because p1 and p2 will resolve to the
same file in the file system. Assume that the file denoted by path C:\abc.txt does not exist. The isSameFile(p3, p4)
method call returns true because both paths are textually equal. The output depends on the existence and
non-existence of these files. The program may print the stack trace of an error if it does not find files at the same
location. Please change the file paths in the program to play with these methods. If you are running the program on
the platform other than Windows, you must change the file path to conform to the path syntax used on your platform.
Listing 10-3. Checking If Two Paths Will Locate the Same File
// SameFileTest.java
package com.jdojo.nio2;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class SameFileTest {
public static void main(String[] args) {
// Assume that C:\poems\luci1.txt file exists
Path p1 = Paths.get("C:\\poems\\luci1.txt");
Path p2 = Paths.get("C:\\poems\\..\\poems\\luci1.txt");
// Assume that C:\abc.txt file does not exist
Path p3 = Paths.get("C:\\abc.txt");
Path p4 = Paths.get("C:\\abc.txt");
 
Search WWH ::




Custom Search