We talk about java 1.6 here. Since symoblic link is not yet supported, how can examine the existence of them.
1: tell wheather the link file itself exists (return tr
looks that way for now... unless you go with openjdk http://openjdk.java.net/projects/nio/javadoc/java/nio/file/attribute/BasicFileAttributes.html#isSymbolicLink()
hmm..not yet supported..will it ever be supported is the question that comes to my mind looking at this question...symbolic links are platform specific and Java is supposed to b platform independent. i doubt if anything of the sort is possible with java as such..you may have to resort to native code for this portion and use JNI to bridge it with the rest of your program in java.
#2 is easy: just use File.isFile
etc., which will traverse the link. The hard part is #1.
So if you cannot use java.nio.file
, and want to avoid JNI etc., the only thing I found which works:
static boolean exists(File link) {
File[] kids = link.getParentFile().listFiles();
return kids != null && Arrays.asList(kids).contains(link);
}
Not terribly efficient but straightforward.
The following should give you a start:
if (file.exists() && !file.isDirectory() && !file.isFile()) {
// it is a symbolic link (or a named pipe/socket, or maybe some other things)
}
if (file.exists()) {
try {
file.getCanonicalFile();
} catch (FileNotFoundException ex) {
// it is a broken symbolic link
}
}
EDIT : The above don't work as I thought because file.isDirectory() and file.isFile() resolve a symbolic link. (We live and learn!)
If you want an accurate determination, you will need to use JNI to make the relevant native OS-specific library calls.
It is slow but you could compare getAbsolutePath() and getCanonicalPath() of a File. So use only outside a performance critical code path.