Java Check a File is Symlink or Actual File using Apache Commons IO

Tags: FileUtils Apache Commons Apache Commons IO File Symlink

In this Java tutorial we learn how to use the method FileUtils.isSymlink() of Apache Commons IO to check whether a given File is a symlink rather than an actual file.

How to add Apache Commons IO library to your Java project

To use the Apache Commons IO library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'commons-io:commons-io:2.8.0'

To use the Apache Commons IO library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.8.0</version>
</dependency>

To have more information about the Apache Commons IO library you can visit the library home page at commons.apache.org/proper/commons-io/

For example we have an actual file at /etc/test.txt and a symlink /etc/test-symlink.txt. To check if a specified File object is a symlink or not we can use the FileUtils.isSymlink() of Apache Commons IO library as below example Java code.

CheckSymlink.java

import org.apache.commons.io.FileUtils;

import java.io.File;

public class CheckSymlink {
    public static void main(String... args) {
        File file1 = new File("/etc/test.txt");
        File file2 = new File("/etc/test-symlink.txt"); // this file is a symlink

        boolean result1 = FileUtils.isSymlink(file1);
        boolean result2 = FileUtils.isSymlink(file2);

        System.out.println("File " + file1 + " is a symlink result: " + result1);
        System.out.println("File " + file2 + " is a symlink result: " + result2);
    }
}
The output is:
File \etc\test.txt is a symlink result: false
File \etc\test-symlink.txt is a symlink result: true

Happy Coding 😊