链接,符号链接或其他

如前所述,java.nio.file程序包,尤其是Path类是“链接感知”的。每个Path方法要么检测遇到符号链接时的操作,要么提供一个选项,使您可以配置遇到符号链接时的行为。

到目前为止,有关符号或软链接的讨论,但是某些文件系统也支持硬链接。 硬链接比符号链接更具限制性,如下所示:

  • 链接的目标必须存在。

  • 通常在目录上不允许硬链接。

  • 硬链接不允许跨分区或卷。因此,它们不能跨文件系统存在。

  • 硬链接的外观和行为类似于常规文件,因此很难找到它们。

  • 硬链接出于所有 Object 和 Object 与原始文件相同。它们具有相同的文件许可权,时间戳等。所有属性都相同。

由于这些限制,硬链接不像符号链接那样经常使用,但是Path方法可与硬链接无缝地一起使用。

几种方法专门处理链接,并在以下各节中介绍:

创建符号链接

如果文件系统支持,则可以使用createSymbolicLink(路径,路径,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);
}

FileAttributes vararg 使您可以指定在创建链接时自动设置的初始文件属性。但是,此参数仅供将来使用,目前尚未实现。

创建硬链接

您可以使用createLink(Path, Path)方法创建与现有文件的硬链接(或* regular *)。第二个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);

有关更多信息,请参见Managing Metadata

查找链接的目标

您可以使用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