Java Path normalize
In this tutorial we’re going to show how to remove redundant elements from paths using Path from Java NIO API. Learn how normalization works and what are its limitations!
Remove redundant elements (. and ..) from Path
Path path = Paths.get("/proc/../proc/./version"); System.out.printf("'%s'.normalize(): %s%n", path, path.normalize());
Produces:
'/proc/../proc/./version'.normalize(): /proc/version
Protects from going outside of root directory
Path path = Paths.get("/proc/../../.."); System.out.printf("'%s'.normalize(): %s%n", path, path.normalize());
Produces:
'/proc/../../..'.normalize(): /
Watch out for non existing path
Path.normalize() doesn’t go to the filesystem, so its possible to normalize to non-existing path:
Path path = Paths.get("/proc/version/.."); System.out.printf("'%s'.normalize(): %s%n", path, path.normalize());
Here version is a file, so we cannot get outside of it using .. (double dots), but it results with:
'/proc/version/..'.normalize(): /proc
Compare the above code with result of calling Path.toRealPath():
Path path = Paths.get("/proc/version/.."); System.out.printf("'%s'.toRealPath(): %s%n", path, path.toRealPath());
Produces exception:
Exception in thread "main" java.nio.file.FileSystemException: /proc/version/..: Is not a directory
References:
Check out Java IO Tutorial to learn more about Java NIO!