In Java 7 or higher, you can use Files.isSymbolicLink() static method to check whether a directory is a symbolic link:

// directory path
Path path = Paths.get("dir");

// check if directory is symlink
if (Files.isSymbolicLink(path)) {
    System.out.println("Dirctory is a symlink!");
} else {
    System.out.println("Directory is not a symlink!");
}

If you are using legacy I/O API (classes in java.io.* package), you need to do a little extra work:

try {
    // directory path
    File file = new File("/home/attacomsian/atta-java");

    // check if directory is empty
    if (file.isDirectory()) {
        File canon = file.getParent() == null ? file :
                new File(file.getParentFile().getCanonicalFile(), file.getName());
        if (!canon.getCanonicalFile().equals(canon.getAbsoluteFile())) {
            System.out.println("Dirctory is a symlink!");
        } else {
            System.out.println("Dirctory is not not symlink!");
        }
    } else {
        System.out.println("Not a directory!");
    }
} catch (IOException ex) {
    ex.printStackTrace();
}

Note: The above code snippet will only work on UNIX systems. You should always use Files.isSymbolicLink() whenever possible. It works everywhere.

Further Reading

You may be interested in other Java I/O articles:

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also Subscribe to RSS Feed.

Last Updated: