Java文件等于 [英] Java file equals
问题描述
我不知道你们,但至少我预计f1会等于f2在下面的代码,但显然不是这样的情况!你对这个有什么想法?似乎我必须写我自己的equals方法来支持它,对吗?
import java.io. *;
public class FileEquals
{
public static void main(String [] args)
{
File f1 = new File(./ hello。文本);
文件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 是比较绝对路径的平等性(在上面的例子中是这样:
-project\.\hello.txt
some-project\hello.txt
因此,它们自然是不同的。
似乎我必须写我自己的equals方法来支持它,
可能是的,但是首先,你必须知道你想要比较什么?只有路径名吗?路径以这种方式:
f1.getCanonicalPath()。equals(f2.getCanonicalPath())
$但是如果你想要比较两个不同文件的内容,那么是,你应该编写自己的方法 - > 或者只是从互联网上的某处复制。
尊敬
I don't know about you guys but at least I expected that f1 would be equal to f2 in the below code but apparently that's not the case! What's your thoughts about this? It seems like I have to write my own equals method to support it, right?
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));
}
}
解决方案 Not, it's not the case. Because equals is comparing equality of absolute paths (in your case above it is something like:
some-project\.\hello.txt
some-project\hello.txt
So they are naturally different.
It seems like I have to write my own equals method to support it,
right?
Probably yes. But first of all, you have to know what you want to compare? Only pathnames? If yes, compare its canonical path in this way:
f1.getCanonicalPath().equals(f2.getCanonicalPath())
But if you want compare content of two different files, then yes, you should write your own method - or simply just copy from somewhere on the internet.
Regards
这篇关于Java文件等于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!