Determine whether a file is a junction (in Windows) or not?

后端 未结 4 1802
囚心锁ツ
囚心锁ツ 2021-02-13 17:47

I\'ve been searching around trying to find a way to determine if a file is a junction or not, and have not found any satisfactory answers.

First thing I tried was:

4条回答
  •  野的像风
    2021-02-13 17:55

    There can be a way to do it without JNA, if you have the right java, such as Oracle jdk 8. It's dodgy, it can cease to work, but....

    You can get BasicFileAttributes interface related to the link:

    BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
    

    It can happen that this interface implementation is a class sun.nio.fs.WindowsFileAttributes. And this class has a method isReparsePoint, which returns true for both junction points and symbolic links. So you can try to use reflection and call the method:

        boolean isReparsePoint = false;
        if (DosFileAttributes.class.isInstance(attr))
            try {
                Method m = attr.getClass().getDeclaredMethod("isReparsePoint");
                m.setAccessible(true);
                isReparsePoint = (boolean) m.invoke(attr);
            } catch (Exception e) {
                // just gave it a try
            }
    

    Now you only can discover whether it really is symbolic link: Files.isSymbolicLink(path)

    If its not, but it is reparse point, then that's junction.

提交回复
热议问题