可以使用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"); }