Java: check symbolic link file existence

拥有回忆 提交于 2019-11-30 22:59:06

问题


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 wheather underlying file exists.

Is there really no way to realize this except JNI?


回答1:


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




回答2:


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




回答3:


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.




回答4:


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.




回答5:


#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.



来源:https://stackoverflow.com/questions/2175673/java-check-symbolic-link-file-existence

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!