Introduction to JDK File. equal ()

Source: Internet
Author: User

 

We generally compare whether two File objects are in the same File. Generally, java. io. File. equal () is used (). The equal () mentioned here does not compare whether the file content is the same, but whether the two file objects point to the same file.

The File equal () method actually calls compareTo () of the current File system FileSystem ().

    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);    }


We found that there is no Unix/Linux implementation in java. io. FileSystem, and only Win32FileSystem is available. Therefore, this implementation class is called by default. It compares the file name with the absolute path. If two File objects have the same getPath (), they are considered to be the same File. In addition, Windows isCase Insensitive.

The following describes java. io. Win32FileSystem. compare ().

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


In this way, the absolute path is used to check whether two objects point to the same file. This method can be used in most cases, but be careful. For example, in Linux, the file name is case sensitive and cannot be ignore. In addition, files created through hard links actually point to the same File, but in File. equal (), it is false.

Therefore, java. nio. file. Files is introduced after JDK1.7. You can use isSameFile () to determine whether two file objects point to the same file.

    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();    }

It obtains the provider of the current system and calls its isSameFile () for verification. The following FileSystem implementation hierarchy:

Java. nio. file. spi. FileSystemProvider

Sun. nio. fs. AbstractFileSystemProvider

Sun. nio. fs. UnixFileSystemProvider

Sun. nio. fs. LinuxFileSystemProvider

Sun. nio. fs. WindowsFileSystemProvider

 

Let's take a look at how UnixFileSystemProvider. isSameFile () is implemented:

    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);    }


He first calls UnixPath. equal (), then checks the readability of the two files, and finally calls UnixFileAttributes. isSameFile (). Obviously, he will first check whether the absolute paths of the two files are the same (Case Sensitive). If the two files are the same, they are considered to be the same file. If the two files are different, check the iNode numbers of the two files. This is a feature of Unix file systems. Files are identified by iNode. If the iNode number is the same, it indicates pointing to the same file. Therefore, you can determine whether two hard links point to the same file.

------------------------ 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));    }


For Windows systems, it is similar. Let's take a look at WindowsFileSystemProvider. isSameFile (), WindowsPath. equal (), and WindowsFileAttributes. isSameFile ().

Determine the absolute path of the file first (Case Insensitive). If they are equal, they are considered to be the same file. If they are not equal, the underlying judgment is performed again. The judgment of the underlying Windows file is done by checking whether the disk number is equal.

------------------------ 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);    }

This makes it clear that you can use File. equal () to compare whether the absolute path of the File is equal (not the content (). If you want to compare whether the OS points to the same file, you can use Files. isSameFile (), which takes into account the differences between different file systems. At the same time, by observing the different implementations of the two system verification rules, we can also peat the differences between different OS file systems. If you are interested, you can further study it!

Finally, let's add an OpenJava Source Code address. You can find the source code of many sun. xxx. xxx referenced by JDK. For example, a series of sun. nio. fs. xxx mentioned above. Http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/sun/awt/shell/ShellFolder.java#ShellFolder.compareTo%28java.io.File%29

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.