Java Programming Tutorials

Java programming tutorials with many code examples!

Java Path comparison

Java Path comparison

In this tutorial we’re going to show how to compare Java Path with other paths and strings. Very useful when finding files on filesystem.

Compare to other Path/string

Path.compareTo() methods compare paths lexicographically and don’t access file system to check whether file exists or not.

Compare to different path

Path path = Paths.get("/proc/version");
Path other = Paths.get("/vmlinuz");
System.out.printf("%s.compareTo(%s): %d%n",
    path, other, path.compareTo(other));

Result:

/proc/version.compareTo(/vmlinuz): -6

Compare to relative path

Path path = Paths.get("/proc/version");
Path other = Paths.get("/proc/./version");
System.out.printf("%s.compareTo(%s): %d%n",
    path, other, path.compareTo(other));

Result:

/proc/version.compareTo(/proc/./version): 72

Redundant elements are not removed, so use Path normalization before comparison.

Compare to the same path

Path path = Paths.get("/proc/version");
Path other = Paths.get("/proc/version");
System.out.printf("%s.compareTo(%s): %d%n",
    path, other, path.compareTo(other));

Result:

/proc/version.compareTo(/proc/version): 0

Path ends with something

Path.endsWith(Path)

Path path = Paths.get("/proc/version");
Path version = Paths.get("version");
System.out.printf("%s.endsWith(%s): %s%n",
    path, version, path.endsWith(version));

Result:

/proc/version.endsWith(version): true

Path.endsWith(“string”)

Path path = Paths.get("/proc/version");
System.out.printf("%s.endsWith(\"version\"): %s%n",
    path, path.endsWith("version"));

Result:

/proc/version.endsWith("version"): true
Path path = Paths.get("/proc/version");
System.out.printf("%s.endsWith(\"something\"): %s%n",
    path, path.endsWith("something"));

Result:

/proc/version.endsWith("something"): false

Path starts with Path/string

Path.startsWith(Path)

Path path = Paths.get("/proc/version");
Path other = Paths.get("/proc");
System.out.printf("%s.startsWith(%s): %s%n",
    path, other, path.startsWith(other));

Result:

/proc/version.startsWith(/proc): true

Path.startsWith(“string”)

Path path = Paths.get("/proc/version");
System.out.printf("%s.startsWith(\"/proc\"): %s%n",
    path, path.startsWith("/proc"));

Result:

/proc/version.startsWith("/proc"): true

References:

Share with the World!