【发布时间】:2015-07-01 17:00:11
【问题描述】:
我想确保两个 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 代码有问题吗?当我跑步时它会给我一个警告。
【问题讨论】:
-
它给出了哪个警告?
-
问题是捕获
Exception是危险的并且可能会掩盖其他问题 -
查看link。
标签: java file-comparison