I am scanning all directories starting from "/" to find some particular directories like "MYFOLDER". However, the folder is that I get double instances of the same folder. This occurs because one folder is located in "/mnt/sdcard/MYFOLDER" and the same folder has a symbolic link in "/sdcard/MYFOLDER"..
My Question is, "Is there any way to determine whether the folder is a symbolic link or not?". Please give me some suggestions..
Simplest way: cd to where the symbolic link is located and do ls -l to list the details of the files. The part to the right of -> after the symbolic link is the destination to which it is pointing. Here we have "Link to temp. txt" that points to ( -> ) "/home/user/temp.
Detecting a Symbolic Link To determine whether a Path instance is a symbolic link, you can use the isSymbolicLink(Path) method. The following code snippet shows how: Path file = ...; boolean isSymbolicLink = Files. isSymbolicLink(file);
In order to follow symbolic links, you must specify ls -L or provide a trailing slash. For example, ls -L /etc and ls /etc/ both display the files in the directory that the /etc symbolic link points to. Other shell commands that have differences due to symbolic links are du, find, pax, rm and tar.
This is essentially how they do in Apache Commons (subject to their license):
public static boolean isSymlink(File file) throws IOException {
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());
}
Edit thanks to @LarsH comment. The above code only checks whether the children file is a symlink.
In order to answer the OP question, it's even easier:
public static boolean containsSymlink(File file) {
return !file.getCanonicalFile().equals(file.getAbsoluteFile());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With