Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 1.6 - determine symbolic links

Tags:

java

java-6

In a DirectoryWalker class I want to find out if a File instance is actually a symbolic link to a directory (assuming, the walker walks on UNIX systems). Given, I already know the instance is a directory, would the following be a reliable condition to determine the symbolic link?

File file; // ...       if (file.getAbsolutePath().equals(file.getCanonicalPath())) {     // real directory ---> do normal stuff       } else {     // possible symbolic link ---> do link stuff } 
like image 229
mats Avatar asked May 01 '09 23:05

mats


People also ask

What is Java symbolic link?

Java Input/Output. Files IO. A symbolic link (also known as symlink or soft link) is a special file that serves as a reference to another file. In this Java tutorial, we will learn to create, detect and find targets of the symbolic links using examples. It is worth noting Java NIO classes (such as Path) are link-aware.

How do I find symbolic links in Windows?

In Command Prompt, run this command: dir /AL /S c:\ A list of all of the symbolic links in the c:\ directory will be returned.


2 Answers

The technique used in Apache Commons uses the canonical path to the parent directory, not the file itself. I don't think that you can guarantee that a mismatch is due to a symbolic link, but it's a good indication that the file needs special treatment.

This is Apache code (subject to their license), modified for compactness.

public static boolean isSymlink(File file) throws IOException {   if (file == null)     throw new NullPointerException("File must not be null");   File canon;   if (file.getParent() == null) {     canon = file;   } else {     File canonDir = file.getParentFile().getCanonicalFile();     canon = new File(canonDir, file.getName());   }   return !canon.getCanonicalFile().equals(canon.getAbsoluteFile()); } 
like image 72
erickson Avatar answered Sep 18 '22 07:09

erickson


Java 1.6 does not provide such low level access to the file system. Looks like NIO 2, which should be included in Java 1.7, will have support for symbolic links. A draft of the new API is available. Symbolic links are mentioned there, creating and following them is possible. I'm not exactly sure that which method should be used to find out whether a file is a symbolic link. There's a mailing list for discussing NIO 2 - maybe they will know.

like image 32
Esko Luontola Avatar answered Sep 20 '22 07:09

Esko Luontola