Finally, File implements the java.lang.Comparable interface’s compareTo() method and overrides
equals() and hashCode(). Table 11-5 describes these miscellaneous methods.
Table 11-5. File's Miscellaneous Methods
Method Description
int compareTo(File pathname) Compares two pathnames lexicographically. The ordering defined by this
method depends upon the underlying platform.
比较两个路径名字典序。
On Unix/Linux platforms,alphabetic case is significant when comparing pathnames; on Windows
platforms, alphabetic case is insignificant. Returns zero when pathname’sabstract pathname equals this File object’s abstract pathname, a negative
value when this File object’s abstract pathname is less than pathname, and
a positive value otherwise. To accurately compare two File objects, call
getCanonicalFile() on each File object and then compare the returned
File objects.
boolean equals(Object obj)) Compares this File object with obj for equality. Abstract pathname equality
depends upon the underlying platform. On Unix/Linux platforms, alphabetic
case is significant when comparing pathnames; on Windows platforms,
alphabetic case is insignificant. Returns true if and only if obj is not null and
is a File object whose abstract pathname denotes the same file/directory as
this File object’s abstract pathname.
当且仅当obj非null且是一个File对象(它的抽象路径名与这个File对象的抽象路径名表示同一个文件/目录)时返回true。
int hashCode() Calculates and returns a hash code for this pathname. This calculation
depends upon the underlying platform. On Unix/Linux platforms, a
pathname’s hash code equals the exclusive OR of its pathname string’s hash
code and decimal value 1234321. On Windows platforms, the hash code is
the exclusive OR of the lowercased pathname string’s hash code and
decimal value 1234321. The current locale (geographical, political, or cultural
region) is not taken into account when lowercasing the pathname string.
计算并返回这个路径名的hash码。
Listing 11-8 presents an application that demonstrates compareTo() along with getCanonicalFile().
Listing 11-8. Comparing Files
import java.io.File;
import java.io.IOException;
public class Compare
{
public static void main(String[] args) throws IOException
{
if (args.length != 2)
{
System.err.println("usage: java Compare filespec1 filespec2");
return;
}
File file1 = new File(args[0]);
File file2 = new File(args[1]);
System.out.println(file1.compareTo(file2));
System.out.println(file1.getCanonicalFile()
.compareTo(file2.getCanonicalFile()));
}
}
Compile Listing 11-8 (javac Compare.java). Assuming successful compilation and a Windows
platform, execute the following command line:
java Compare Compare.class .\Compare.class
You should observe the following output:
53
0
The 53 indicates that file1’s abstract pathname is lexicographically greater than file2’s abstract
pathname. However, when comparing their canonical representations, these abstract pathnames are
considered to be identical (as indicated by the 0).