In Java 7 or higher, you can use the Files.isSymbolicLink()
static method to check whether a directory is a symbolic link:
// directory path
Path path = Paths.get("dir");
// check if the directory is a symlink
if (Files.isSymbolicLink(path)) {
System.out.println("Directory is a symlink!");
} else {
System.out.println("Directory is not a symlink!");
}
If you are using legacy I/O API (classes in the 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:
- Reading and Writing Files in Java
- How to Read and Write Text Files in Java
- How to Read and Write Binary Files in Java
- Reading and Writing Files using Java NIO API
- How to read a file line by line in Java
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.