File类int compareTo(File filepath) (File Class int compareTo(File filepath))
This method is available in package java.io.File.compareTo(File obj).
软件包java.io.File.compareTo(File obj)中提供了此方法。
This method is used to compare two filepath or files whether they are lexicographically equal or not.
此方法用于比较两个文件路径或文件,无论它们在字典上是否相等。
The return type is int that means if it returns 0 then both files are equal if it returns negative value then the first argument will be less than the given argument and if it returns greater than 0 then the first argument will be greater than 0.
返回类型为int ,这意味着如果返回0,则两个文件相等;如果返回负值,则第一个参数将小于给定参数;如果返回大于0,则第一个参数将大于0。
Syntax:
句法:
int compareTo(File filepath){
}
Parameter(s):
参数:
We pass only one object as a parameter in the method of the File i.e filepath. This argument will be compared with other arguments.
在File方法中,我们仅传递一个对象作为参数,即filepath。 该参数将与其他参数进行比较。
Return value:
返回值:
The return type of this method is int. So, it returns integer value(0, greater than 0, or less than 0).
此方法的返回类型为int 。 因此,它返回整数值(0,大于0或小于0)。
Java程序演示compareTo()方法的示例 (Java program to demonstrate example of compareTo() method)
// import the File class because we will use File class methods
import java.io.File;
// import the Exception class because it may raise
// an exception when working with files
import java.lang.Exception;
public class CompareFile {
public static void main(String[] args) {
try {
// Specify the path of file and we use double slashes to
// escape '\' character sequence for windows otherwise
// it will be considerable as url.
int compare;
// creating two file object with absolute path
File file1 = new File("E:\\Programs\\myjava.txt");
File file2 = new File("E:\\Programs\\myjava1.txt");
// By using compareTo(file2) this method will return
// negative integer because file1 length will be less
// than the file2
compare = file1.compareTo(file2);
if (compare == 0)
System.out.println("Both files are equal");
if (compare < 0)
System.out.println("file1 is less than file2");
if (compare > 0)
System.out.println("file1 is greater than file2");
} catch (Exception e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output
输出量
E:\Programs>javac CompareFile.java
E:\Programs>java CompareFile
file1 is less than file2
翻译自: https://www.includehelp.com/java/file-class-int-compareto-file-filepath-method-with-example.aspx