在 Java 中比较两个文件路径
可以使用 java.io.File.compareTo() 方法在 Java 中按字典顺序比较两个文件路径。该方法需要一个参数,即要比较的抽象路径名。如果两个文件路径名相等,则返回 0。
下面给出了一个演示的程序 -
示例
import java.io.File;
public class Demo {
public static void main(String[] args) {
File file1 = new File("C:/File/demo1.txt");
File file2 = new File("C:/File/demo1.txt");
if (file1.compareTo(file2) == 0) {
System.out.println("Both the paths are lexicographically equal");
} else {
System.out.println("Both the paths are lexicographically not equal");
}
}
}以上程序的输出如下 -
输出
Both the paths are lexicographically equal
现在让我们来理解一下上面的程序。
方法 java.io.File.compareTo() 用于按字典顺序比较两个文件路径。如果方法返回 0,则文件路径按字典顺序相等,否则不相等。下面给出了一个演示代码段 -
File file1 = new File("C:/File/demo1.txt");
File file2 = new File("C:/File/demo1.txt");
if (file1.compareTo(file2) == 0) {
System.out.println("Both the paths are lexicographically equal");
} else {
System.out.println("Both the paths are lexicographically not equal");
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP