[NIO.2] 第二十二篇 创建硬链接

可以调用 createLink() 方法创建硬链接,它将会创建已存在文件的硬链接。这个方法返回新链接的 Path 对象,你可以使用这个 Path 对象来访问文件。

如果你的文件系统不支持硬链接,那么将会抛出 UnsupportedOperationException 异常。另外,要记住,硬链接只能为已存在的文件创建。

下面的代码演示了如何创建一个硬链接,名为 rafael.nadal.4 目标文件为 C:\rafaelnadal\photos\rafa_winner.jpg(这个文件必须存在,并且文件系统必须有创建硬链接的权限)。

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) {
Path link = FileSystems.getDefault().getPath("rafael.nadal.4");
Path target = FileSystems.getDefault().getPath("C:/rafaelnadal/photos", "rafa_winner.jpg");

try {
Files.createLink(link, target);
System.out.println("The link was successfully created!");
} catch (IOException | UnsupportedOperationException | SecurityException e) {
if (e instanceof SecurityException) {
System.err.println("Permission denied!");
}
if (e instanceof UnsupportedOperationException) {
System.err.println("An unsupported operation was detected!");
}
if (e instanceof IOException) {
System.err.println("An I/O error occured!");
}
System.err.println(e);
}
}
}


注:如果链接已经存在,那么会抛出 FileAlreadyExistsException 异常。

文章来源:[url]http://www.aptusource.org/2014/04/nio-2-creating-a-hard-link/[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值