Java 文件等于 [英] Java file equals

查看:26
本文介绍了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 文件等于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆