Java Programming Tutorials

Java programming tutorials with many code examples!

Java Path symlink

Java Path symlink

In this tutorial we’re going to show how to use Java Path to work with symbolic links that are common in Linux world.

Resolve Symlink

Let’s use Path.toRealPath() to resolve a /usr/bin/java symlink, that points to /etc/alternatives/java, which is also a symlink, that points to:

Path path = Paths.get("/usr/bin/java");
System.out.printf("'%s'.toRealPath(): %s%n",
                  path, path.toRealPath());

Results:

'/usr/bin/java'.toRealPath(): /usr/lib/jvm/java-8-oracle/jre/bin/java

Path.toRealPath(NOFOLLOW_LINKS)

The same symbolic link, but without following links:

System.out.printf("'%s'.toRealPath(NOFOLLOW_LINKS): %s%n",
                  path, path.toRealPath(NOFOLLOW_LINKS));

Results:

'/usr/bin/java'.toRealPath(NOFOLLOW_LINKS): /usr/bin/java

Again, but this time with redundant elements in between:

Path path = Paths.get("/usr/./bin/java");
System.out.printf("'%s'.toRealPath(NOFOLLOW_LINKS): %s%n",
                  path, path.toRealPath(NOFOLLOW_LINKS));

Results – redundant dot has been removed:

'/usr/./bin/java'.toRealPath(NOFOLLOW_LINKS): /usr/bin/java

Note that toRealPath() also turns relative paths into absolute.

Check out Java IO Tutorial to learn more about Java NIO!

Share with the World!