我不了解你们,但至少我预计在下面的代码中 f1 将等于 f2,但显然情况并非如此!您对此有何看法?看来我得自己写个equals方法来支持了,对吧?
import java.io.*;
public class FileEquals
{
public static void main(String[] args)
{
File f1 = new File("./hello.txt");
File f2 = new File("hello.txt");
System.out.println("f1: " + f1.getName());
System.out.println("f2: " + f2.getName());
System.out.println("f1.equals(f2) returns " + f1.equals(f2));
System.out.println("f1.compareTo(f2) returns " + f1.compareTo(f2));
}
}
最佳答案
不,事实并非如此。因为 equals 正在比较绝对路径的相等性(在您上面的情况下,它类似于:
some-project\.\hello.txt
some-project\hello.txt
所以它们自然是不同的。
It seems like I have to write my own equals method to support it, right?
可能是的。但首先,您必须知道要比较什么?只有路径名?如果是,请以这种方式比较其规范路径:
f1.getCanonicalPath().equals(f2.getCanonicalPath())
但如果您想比较两个不同文件的内容,那么是的,您应该编写自己的方法 - 或者干脆从互联网上的某个地方复制。
关于Java 文件等于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8930859/