本文共 1146 字,大约阅读时间需要 3 分钟。
File类int compareTo(File filepath)软件包java.io.File.compareTo(File obj)中提供了此方法。
此方法用于比较两个文件路径或文件,无论它们在字典上是否相等。
返回类型为int,这意味着如果返回0,则两个文件相等;如果返回负值,则第一个参数将小于给定参数;如果返回大于0,则第一个参数将大于0。
语法:int compareTo(File filepath){
}
参数:
在File方法中,我们仅传递一个对象作为参数,即filepath。该参数将与其他参数进行比较。
返回值:
此方法的返回类型为int。因此,它返回整数值(0,大于0或小于0)。
Java程序演示compareTo()方法示例//导入File类,因为我们将使用File类方法
import java.io.File;
//导入Exception类,因为它可能引发
//处理文件时出现异常
import java.lang.Exception;
public class CompareFile {
public static void main(String[] args) {
try {
//指定文件的路径,我们使用双斜杠
//为Windows转义'\'字符序列
int compare;
//用绝对路径创建两个文件对象
File file1 = new File("E:\\Programs\\myjava.txt");
File file2 = new File("E:\\Programs\\myjava1.txt");
//通过使用compareTo(file2),此方法将返回
//负整数,因为file1的长度将小于
//比文件2-
compare = file1.compareTo(file2);
if (compare == 0)
System.out.println("Both files are equal");
if (compare
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();
}
}
}
输出结果E:\Programs>javac CompareFile.java
E:\Programs>java CompareFile
file1 is less than file2
转载地址:https://blog.csdn.net/weixin_32601635/article/details/114924673 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!