java如何判断一个linux下的文件是否为链接文件。
public static boolean isLink(File file) {
String cPath = "";
try {
cPath = file.getCanonicalPath();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
return !cPath.equals(file.getAbsolutePath());
}
如果是普通文件,file.getAbsolutePath()和file.getCanonicalPath()是一样的。
如果是link文件,file.getAbsolutePath()是链接文件的路径;file.getCanonicalPath是实际文件的路径(所指向的文件路径)。
* 例子:
/root/dir1/file1 -> /root/dir2/file2
比如在/root/dir3/program/有测试程序,用来测试/root/dir1/file1是否为link文件,运行java -jar program.jar /root/dir1/file1,
可以得到absolutePath:/root/dir1/file1,而canonicalPath:/root/dir2/file2;
运行java -jar program.jar ../../dir1/file1,
可以得到absolutePath:/root/dir3/program/../../dir1/file1,而canonicalPath:/root/dir2/file2;