讨论JDK的File.equal()

讨论JDK的File.equal()

大家好,又见面了,我是全栈君。

 

         我们一般比较两个文件中的对象是相同的文件,通常使用java.io.File.equal()。这里,equal()是不是文件内容的比较结果为。象是否指向同一个文件

         File的equal()方法。实际上调用了当前文件系统FileSystem的compareTo()。

    public boolean equals(Object obj) {
        if ((obj != null) && (obj instanceof File)) {
            return compareTo((File)obj) == 0;
        }
        return false;
    }
    static private FileSystem fs = FileSystem.getFileSystem();
    public int compareTo(File pathname) {
        return fs.compare(this, pathname);
    }

         我们发现,java.io.FileSystem中没有对Unix/Linux的实现,仅仅有Win32FileSystem,所以都是默认调用的这个实现类。 它对文件的比較,事实上就是对文件名称和绝对路径的比較。

假设两个File对象有同样的getPath(),就觉得他们是同一个文件。并且能看出来,Windows是不区分大写和小写的。

如以下的java.io.Win32FileSystem.compare()。

    public int compare(File f1, File f2) {
        return f1.getPath().compareToIgnoreCase(f2.getPath());
    }

         这样通过比較绝对路径来检验两个对象是否指向同一个文件的方法,能适用大部分的情况,但也要小心。比方说,Linux以下,文件名称对大写和小写是敏感的,就不能ignore了。并且通过硬链接建立的文件,实质还是指向同一个文件的,可是在File.equal()中却为false

         所以在JDK1.7后引入了工具类java.nio.file.Files,能够通过isSameFile()来推断两个文件对象是否指向同一个文件。

    public boolean isSameFile(Path path, Path path2) throws IOException {        return provider(path).isSameFile(path, path2);     }    private static FileSystemProvider provider(Path path) {        return path.getFileSystem().provider();    }

         他是获取当前系统的provider,再调用其isSameFile()来校验的。以下的FileSystem的实现层次结构:

        java.nio.file.spi.FileSystemProvider

            sun.nio.fs.AbstractFileSystemProvider

                sun.nio.fs.UnixFileSystemProvider

                    sun.nio.fs.LinuxFileSystemProvider

                sun.nio.fs.WindowsFileSystemProvider

 

我们先看看UnixFileSystemProvider.isSameFile() 是怎么实现的:

    public boolean isSameFile(Path obj1, Path obj2) throws IOException {        UnixPath file1 = UnixPath.toUnixPath(obj1);        if (file1.equals(obj2))            return true;         file1.checkRead();file2.checkRead();        UnixFileAttributes attrs1 = UnixFileAttributes.get(file1, true);        UnixFileAttributes attrs2 = UnixFileAttributes.get(file2, true);        return attrs1.isSameFile(attrs2);    }

         他先调用了UnixPath.equal(),然后检查两个文件的可读性,最后再调用了UnixFileAttributes.isSameFile()。

非常显然,他会先检查两个文件的绝对路径是否同样(大写和小写敏感),假设同样的话,就觉得两者是同一个文件。假设不同,再检查两个文件的iNode号。

这是Unix文件系统的特点,文件是通过iNode来标识的,仅仅要iNode号同样,就说明指向同一个文件。

所以能用在推断两个硬链接是否指向同一个文件。

————————UnixPath————————

    public boolean equals(Object ob) {
        if ((ob != null) && (ob instanceof UnixPath))
            return compareTo((Path)ob) == 0;    // compare two path
        return false;
    }
    public int compareTo(Path other) {
        int len1 = path.length;
        int len2 = ((UnixPath) other).path.length;
        int n = Math.min(len1, len2);
        byte v1[] = path;
        byte v2[] = ((UnixPath) other).path;
        int k = 0;
        while (k < n) {
            int c1 = v1[k] & 0xff;
            int c2 = v2[k] & 0xff;
            if (c1 != c2)
                return c1 - c2;
        }
        return len1 - len2;
    }

————————UnixFileAttributes————————

    boolean isSameFile(UnixFileAttributes attrs) {
        return ((st_ino == attrs.st_ino) && (st_dev == attrs.st_dev));
    }

         而对于Windows系统。也是大同小异,来看看WindowsFileSystemProvider.isSameFile(),WindowsPath.equal()和 WindowsFileAttributes.isSameFile()。

         都是先推断文件绝对路径(忽略大写和小写),假设相等就觉得是同一个文件;假设不等就再进行底层推断。Windows底层文件的推断是检查磁盘号是否相等来完毕的。

———————— WindowsFileSystemProvider————————

    public boolean isSameFile(Path obj1, Path obj2) throws IOException {
        WindowsPath file1 = WindowsPath.toWindowsPath(obj1);
        if (file1.equals(obj2))
            return true;
 
        file1.checkRead();file2.checkRead();
        WindowsFileAttributes attrs1 =WindowsFileAttributes.readAttributes(h1); 
        WindowsFileAttributes attrs2 =WindowsFileAttributes.readAttributes(h2);
        return WindowsFileAttributes.isSameFile(attrs1, attrs2);
    }

———————— WindowsPath ————————  

    public boolean equals(Object obj) {
        if ((obj != null) && (obj instanceof WindowsPath))
            return compareTo((Path)obj) == 0;
        return false;
    }
    public int compareTo(Path obj) {
        if (obj == null)
            throw new NullPointerException();
        String s1 = path;
        String s2 = ((WindowsPath)obj).path;
        int n1 = s1.length();
        int n2 = s2.length();
        int min = Math.min(n1, n2);
        for (int i = 0; i < min; i++) {
            char c1 = s1.charAt(i);
            char c2 = s2.charAt(i);
             if (c1 != c2) {
                 c1 = Character.toUpperCase(c1);
                 c2 = Character.toUpperCase(c2);
                 if (c1 != c2)
                     return c1 - c2;
             }
        }
        return n1 - n2;
    }

———————— WindowsFileAttributes————————

    static boolean isSameFile(WindowsFileAttributes attrs1, WindowsFileAttributes attrs2) {
        // volume serial number and file index must be the same
        return (attrs1.volSerialNumber == attrs2.volSerialNumber) &&
            (attrs1.fileIndexHigh == attrs2.fileIndexHigh) &&
            (attrs1.fileIndexLow == attrs2.fileIndexLow);
    }

    

         这样一比較就清晰了。假设仅仅是对照文件的绝对路径是否相等(不是内容)。能够放心使用File.equal()。而假设要比較在OS中是否指向同一个文件。能够使用Files.isSameFile()。它考虑到了不同文件系统的差异。同一时候。我们通过观察这两种系统校验规则的不同实现,也能窥视到不同OS文件系统的差异。假设你有兴趣,能够进一步深入研究哦!

         最后,付上一个OpenJava的源代码地址,你能够在里面找到JDK引用的非常多sun.xxx.xxx的源代码。比如上面提到的一系列sun.nio.fs.xxx。http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/sun/awt/shell/ShellFolder.java#ShellFolder.compareTo%28java.io.File%29

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/116665.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • XR应用场景骤变,一场波及5亿人的新探索开始了「建议收藏」

    XR应用场景骤变,一场波及5亿人的新探索开始了「建议收藏」鱼羊明敏发自凹非寺量子位|公众号QbitAI如果说有什么事可以最快逼疯一个远程办公人,那“线上开会”肯定会得高票。网络卡顿、沟通低效导致会议变得长长长长长……万一碰上出门在外的紧急情况,更是当场抓瞎。这时候,就让人禁不住幻想,要是有副科幻大片同款高端眼镜,一戴上就能随时办公,那感觉可就起飞了。于是,打从元宇宙这股风起,大到国际科技巨头,小到国内初创企业,就没少…

    2022年6月14日
    35
  • input file读取文件

    input file读取文件js读取inputfile文件的两种方式:&lt;divid="localImag"&gt;&lt;imgid="preview"src=""width="150"height="180"style="display:block;width:150px;height:180px;"&gt;&lt;

    2022年7月17日
    14
  • java数组去重方法是,java数组去重的两种方法

    java数组去重方法是,java数组去重的两种方法我们对于数组元素的使用,有时候在创建数组的初期,并没有考虑过元素的重复问题。当我们想要不重复元素的数组时,就要再进行一步去重的工作。数组的去重有两种方法可以实现,一个是循环比较,另一个是hashSet的集合方法。下面我们就这两种Java数组去重的方法带来详解。1、循环比较循环对比每个元素的值是否一致,这个就不过多去介绍,主要是第2种方法2、利用hashSet去重hashSet是一个没有重复元素的集…

    2022年6月22日
    75
  • Django(57)Generic类视图[通俗易懂]

    Django(57)Generic类视图[通俗易懂]前言上篇我们通过mixin可以非常方便的实现一些CURD操作。实际上针对这些mixin,DRF还进一步的进行了封装,放到generics下。有以下generic类视图:generics.ListA

    2022年7月29日
    10
  • countdown timer plus_android studio计时器

    countdown timer plus_android studio计时器Inthisandroidcountdowntimerexample,we’llimplementatimerobjecttodisplaytheprogressinaProgressBar.Theapplicationwe’llbuildinthistutorialisausefulcomponentinQuizappswhere…

    2025年11月25日
    2
  • Apache中 RewriteCond 规则参数介绍[通俗易懂]

    Apache中 RewriteCond 规则参数介绍[通俗易懂]Apache中RewriteCond语句对于我来说一直是个难点,多次试图去把它搞明白,都没有结果,这次我终于算大概知道它的意思了。RewriteCond就像我们程序中的if语句一样,表示如果符合某个或某几个条件则执行RewriteCond下面紧邻的RewriteRule语句,这就是RewriteCond最原始、基础的功能,为了方便理解,下面来看看几个例子。RewriteEngineonRewriteCond%{HTTP_USER_AGENT}^Mozilla\/5\.0.*Rew…

    2022年6月10日
    30

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号