两个文件指向同一个文件吗?

Are two File pointing to the same file?

我想确保两个 java.io.File 没有指向同一个文件, 试过各种方法,终于找到了办法,但我要确保没有漏洞。

这很重要,因为我正在尝试编写一个程序来删除重复的文件,我不想因为两个 java.io.File 指向同一个文件而最终删除一个唯一的文件。

File f1 = new File("file.txt");
File f2 = new File("./file.txt");
//these methods can't tell it's the same file
System.out.println(f1.compareTo(f2)); // 56 which mean not equal
System.out.println(f1.equals(f2)); // false
System.out.println(f1 == f2); // false
System.out.println(f1.getAbsolutePath().compareTo(f2.getAbsolutePath())); // 56

// this method can tell it's the same file... hopefully.
try{
    System.out.println(f1.getCanonicalPath().compareTo(f2.getCanonicalPath())); // 0
}catch (Exception e){
    e.printStackTrace();
}

另外,我的try-catch代码有问题吗?当我 运行.

时它会给我一个警告

是的,这应该有效。来自 the documentation:

A canonical pathname is both absolute and unique. The precise definition of canonical form is system-dependent. This method first converts this pathname to absolute form if necessary, as if by invoking the getAbsolutePath() method, and then maps it to its unique form in a system-dependent way. This typically involves removing redundant names such as "." and ".." from the pathname, resolving symbolic links (on UNIX platforms), and converting drive letters to a standard case (on Microsoft Windows platforms).

所以这个方法应该处理:

  • 冗余路径部分,例如/./
  • 符号链接
  • 相对路径

但我强烈建议您使用 Files.isSameFile:

If both Path objects are equal then this method returns true without checking if the file exists. If the two Path objects are associated with different providers then this method returns false. Otherwise, this method checks if both Path objects locate the same file, and depending on the implementation, may require to open or access both files.

主要是因为 java.io.File API 有大量细微的错误和 API 无法解决的问题。还因为它内置了执行大多数常见任务的方法。