Java: check symbolic link file existence

后端 未结 5 752
醉梦人生
醉梦人生 2021-01-11 13:58

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

相关标签:
5条回答
  • 2021-01-11 14:32

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

    0 讨论(0)
  • 2021-01-11 14:36

    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.

    0 讨论(0)
  • 2021-01-11 14:42

    #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 讨论(0)
  • 2021-01-11 14:46

    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.

    0 讨论(0)
  • 2021-01-11 14:52

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

    0 讨论(0)
提交回复
热议问题