Java file equals(Java 文件等于)
问题描述
我不了解你们,但至少我预计在下面的代码中 f1 将等于 f2,但显然情况并非如此!您对此有何看法?看来我得自己写个equals方法来支持了,对吧?
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));
}
}
推荐答案
不,不是这样的.因为 equals 正在比较绝对路径的相等性(在您上面的情况下,它类似于:
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-projecthello.txt
所以它们自然是不同的.
So they are naturally different.
看来我必须编写自己的equals方法来支持它,对吧?
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.
这篇关于Java 文件等于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 文件等于
基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01