链接、符号和其他
如前所述,java.nio.file
包,尤其是 Path
类,是“链接感知”的。每个 Path
方法要么检测到遇到符号链接时该怎么做,要么提供一个选项,使您能够在遇到符号链接时配置行为。
到目前为止的讨论都是关于符号链接或软链接,但一些文件系统也支持硬链接。硬链接比符号链接更严格,如下所示
- 链接的目标必须存在。
- 硬链接通常不允许在目录上。
- 硬链接不允许跨分区或卷。因此,它们不能跨文件系统存在。
- 硬链接看起来像普通文件,并且表现得像普通文件,因此很难找到它们。
- 硬链接本质上与原始文件是同一个实体。它们具有相同的文件权限、时间戳等。所有属性都相同。
由于这些限制,硬链接不像符号链接那样经常使用,但 Path
方法与硬链接无缝协作。
创建符号链接
如果您的文件系统支持,您可以使用 createSymbolicLink(Path, Path, FileAttribute)
方法创建符号链接。第二个 Path
参数表示目标文件或目录,可能存在也可能不存在。以下代码片段创建了一个具有默认权限的符号链接
Path newLink = ...;
Path target = ...;
try {
Files.createSymbolicLink(newLink, target);
} catch (IOException x) {
System.err.println(x);
} catch (UnsupportedOperationException x) {
// Some file systems do not support symbolic links.
System.err.println(x);
}
FileAttribute
可变参数使您可以指定在创建链接时以原子方式设置的初始文件属性。但是,此参数旨在供将来使用,目前尚未实现。
创建硬链接
您可以使用 createLink(Path, Path)
方法为现有文件创建硬链接(或普通链接)。第二个 Path
参数定位现有文件,它必须存在,否则将抛出 NoSuchFileException
。以下代码片段展示了如何创建链接
Path newLink = ...;
Path existingFile = ...;
try {
Files.createLink(newLink, existingFile);
} catch (IOException x) {
System.err.println(x);
} catch (UnsupportedOperationException x) {
// Some file systems do not
// support adding an existing
// file to a directory.
System.err.println(x);
}
检测符号链接
要确定 Path
实例是否为符号链接,您可以使用 isSymbolicLink(Path)
方法。以下代码片段展示了如何
Path file = ...;
boolean isSymbolicLink =
Files.isSymbolicLink(file);
有关更多信息,请参阅部分 管理元数据。
查找链接的目标
您可以使用 readSymbolicLink(Path)
方法获取符号链接的目标,如下所示
Path link = ...;
try {
System.out.format("Target of link" +
" '%s' is '%s'%n", link,
Files.readSymbolicLink(link));
} catch (IOException x) {
System.err.println(x);
}
如果 Path
不是符号链接,此方法将抛出 NotLinkException
。
上次更新: 2023 年 1 月 25 日