JAVA如何找到符号link指向的目标文件路径?

JAVA how to find the target file path that a symbolic link points to?

我试图在 Java 中找到一种方法来找出符号 link 指向的文件路径。 我们有一个系统可以监控一个符号 link 文件夹,根据文件名做一些事情,删除那个符号 link 文件。 我需要做的是找出每个符号 link 文件指向的位置,这样我就可以在符号 link 时删除该文件。 这是在 RHEL 系统上使用 Java。

任何对 API 主题的指导将不胜感激。我的搜索遇到瓶颈。

https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html#toRealPath-java.nio.file.LinkOption...-

Path toRealPath(LinkOption... options) throws IOException Returns the real path of an existing file. The precise definition of this method is implementation dependent but in general it derives from this path, an absolute path that locates the same file as this path, but with name elements that represent the actual name of the directories and the file. For example, where filename comparisons on a file system are case insensitive then the name elements represent the names in their actual case. Additionally, the resulting path has redundant name elements removed.

If this path is relative then its absolute path is first obtained, as if by invoking the toAbsolutePath method.

The options array may be used to indicate how symbolic links are handled. By default, symbolic links are resolved to their final target. If the option NOFOLLOW_LINKS is present then this method does not resolve symbolic links. Some implementations allow special names such as ".." to refer to the parent directory. When deriving the real path, and a ".." (or equivalent) is preceded by a non-".." name then an implementation will typically cause both names to be removed. When not resolving symbolic links and the preceding name is a symbolic link then the names are only removed if it guaranteed that the resulting path will locate the same file as this path.

Parameters: options - options indicating how symbolic links are handled Returns: an absolute path represent the real path of the file located by this object Throws: IOException - if the file does not exist or an I/O error occurs SecurityException - In the case of the default provider, and a security manager is installed, its checkRead method is invoked to check read access to the file, and where this path is not absolute, its checkPropertyAccess method is invoked to check access to the system property user.dir

使用 nio 的 toRealPath() 方法。 NO_FOLLOW_LINKS LinkOption 与您正在尝试做的相反,所以不要使用它。

Path realPath = aFile.toPath().toRealPath()

Path realPath = aPath().toRealPath()

这里有一个问题,与 toAbsolutePath 不同,toRealPath 抛出一个 IOException 因为它实际上必须与文件系统交互才能找到真正的路径。

java.nio.file.Files.readSymbolicLink 可能就是您所需要的。