开发者

Java: check symbolic link file existence

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 true even if the link is broken)

2: follow the link and tell whea开发者_开发百科ther underlying file exists.

Is there really no way to realize this except JNI?


looks that way for now... unless you go with openjdk http://openjdk.java.net/projects/nio/javadoc/java/nio/file/attribute/BasicFileAttributes.html#isSymbolicLink()


It is slow but you could compare getAbsolutePath() and getCanonicalPath() of a File. So use only outside a performance critical code path.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜