… Path link = FileSystems.getDefault().getPath("rafael.nadal.5"); Path target = FileSystems.getDefault().getPath("C:/rafaelnadal/photos", "rafa_winner.jpg"); try { Files.createSymbolicLink(link, target); } catch (IOException | UnsupportedOperationException | SecurityException e) { } //check if a path is a symbolic link - solution 1 boolean link_isSymbolicLink_1 = Files.isSymbolicLink(link); boolean target_isSymbolicLink_1 = Files.isSymbolicLink(target); System.out.println(link.toString() + " is a symbolic link ? " + link_isSymbolicLink_1); System.out.println(target.toString() + " is a symbolic link ? " + target_isSymbolicLink_1); …
上面代码段的运行结果如下:
rafael.nadal.5 is a symbolic link ? true C:\rafaelnadal\photos\rafa_winner.jpg is a symbolic link ? false
也可以通过属性视图来进行检验,basic 视图中有 isSymbolicLink 属性,用来检验是否为软链接。可以使用 readAttributes() 方法来获取 isSymbolicLink 属性(在这里不推荐使用,因为这个方法会返回一组属性列表),更为简单的做法是调用 getAttribute() 方法,如下所示:
… try { boolean link_isSymbolicLink_2 = (boolean) Files.getAttribute(link, "basic:isSymbolicLink"); boolean target_isSymbolicLink_2 = (boolean) Files.getAttribute(target, "basic:isSymbolicLink"); System.out.println(link.toString() + " is a symbolic link ? " + link_isSymbolicLink_2); System.out.println(target.toString() + " is a symbolic link ? "+ target_isSymbolicLink_2); } catch (IOException | UnsupportedOperationException e) { System.err.println(e); } …
运行后,输出结果为:
rafael.nadal.5 is a symbolic link ? true C:\rafaelnadal\photos\rafa_winner.jpg is a symbolic link ? false
文章来源: http://www.aptusource.org/2014/04/nio-2-checking-a-symbolic-link/