代码之家  ›  专栏  ›  技术社区  ›  solotim

Java:检查符号链接文件是否存在

  •  12
  • solotim  · 技术社区  · 16 年前

    我们在这里讨论Java1.6。既然symbolic-link还不受支持,如何检查它们的存在呢。

    2:遵循链接并告知其基础文件是否存在。

    除了JNI,真的没有办法实现这一点吗?

    5 回复  |  直到 16 年前
        1
  •  5
  •   Ryan Fernandes    16 年前
        2
  •  5
  •   user159313    15 年前

    速度很慢,但可以比较文件的getAbsolutePath()和getCanonicalPath()。因此,仅在性能关键的代码路径之外使用。

        3
  •  1
  •   Stephen C    16 年前

    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
        }
    }
    

    编辑

    如果您想要准确地确定,则需要使用JNI进行相关的本机操作系统特定库调用。

        4
  •  1
  •   Aadith Ramia    16 年前

        5
  •  1
  •   Jesse Glick    13 年前

    File.isFile 等,它将遍历链接。最难的部分是#1。

    所以如果你不能使用 java.nio.file

    static boolean exists(File link) {
        File[] kids = link.getParentFile().listFiles();
        return kids != null && Arrays.asList(kids).contains(link);
    }
    

    效率不太高,但很直截了当。

    推荐文章