Comparing Path Objects
The methods in the Path interface for comparing two paths only consult the path strings, and do not access the file system or require that the paths exist in the file system.
boolean equals(Object other)
Determines whether this path is equal to the given object by comparing their path strings. It does not eliminate any redundancies from the paths before testing for equality. See also the Files.isSameFile() method (p. 1306).
int compareTo(Path other)
A Path object implements the Comparable<Path> interface. This method compares two path strings lexicographically according to the established contract of this method. It means paths can be compared, searched, and sorted.
The code below illustrates sorting paths according to their natural order. Comparison of the paths is based purely on comparison of their path strings, as is the equality comparison.
Path p1 = Path.of(“/”, “a”, “b”, “c”, “d”);
Path p2 = Path.of(“/”, “a”, “b”);
Path p3 = Path.of(“/”, “a”, “b”, “c”);
Path p4 = Path.of(“a”, “b”);
// Sorting paths according to natural order:
List<Path> sortedPaths = Stream.of(p1, p2, p3, p4)
.sorted()
.toList();
System.out.println(sortedPaths);
// [/a/b, /a/b/c, /a/b/c/d, a/b]
// Comparing for lexicographical equality:
System.out.println(p2); // Absolute path: /a/b
System.out.println(p3.subpath(0, 2)); // Relative path: a/b
System.out.println(p2.equals(p3.subpath(0, 2))); // false
21.4 Operations on Directory Entries
The static methods of the Files class interact with the file system to access directory entries in the file system. The methods make heavy use of Path objects that denote directory entries.
Characteristics of Methods in the Files Class
It is worth noting certain aspects of the static methods in the Files class, as this will aid in using and understanding the operations they perform.
Handling System Resources
The NIO.2 API uses many resources, such as files and streams, that should be closed after use to avoid any degradation of performance due to lack of system resources. As these resources implement the java.io.Closeable interface, they are best handled in a try-with-resources statement that guarantees to close them after its execution.
Leave a Reply