Java中的路径 compareTo() 方法及示例
Java Path 接口是在Java 7 中添加到Java NIO 中的。Path 接口位于Java.nio.file 包中,因此Java Path 接口的全称是Java.nio.file.Path。 Java Path 实例表示文件系统中的路径。路径可以用来定位文件或目录。实体的路径可以有两种类型,一种是绝对路径,另一种是相对路径。绝对路径是从根到实体的位置地址,而相对路径是相对于其他路径的位置地址。
java .nio.file.Path 的compareTo(Java.nio.file.Path)Java用于按字典顺序比较两个抽象路径。通过这种方法可以比较两条路径。此方法定义的路径顺序是特定于提供者的,并且在默认提供者的情况下,是特定于平台的。如果参数等于此路径,则此方法返回零,如果此路径按字典顺序小于参数,则返回小于零的值,如果此路径按字典顺序大于参数,则返回大于零的值。此方法不访问文件系统。不需要文件就必须存在。此方法不能用于比较与不同文件系统提供程序关联的路径。
句法:
int compareTo(Path other)
参数:此方法接受单个参数另一个路径,该路径是与当前路径相比的路径。
返回值:如果参数等于此路径,则此方法返回零,如果此路径按字典顺序小于参数,则返回小于零的值,如果此路径按字典顺序大于参数,则返回大于零的值。
异常:如果路径与不同的提供者相关联,则此方法抛出和异常ClassCastException 。
下面的程序说明了 compareTo(Java.nio.file.Path) 方法:
方案一:
Java
// Java program to demonstrate
// Path.compareTo(Path) method
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class GFG {
public static void main(String[] args)
throws IOException
{
// create object of Paths
Path path1
= Paths.get("D:","eclipse","configuration","org.eclipse.update");
Path path2
= Paths.get("D:","eclipse","configuration","org.eclipse.update");
// compare paths
int value = path1.compareTo(path2);
// print result
if (value == 0)
System.out.println("Both are equal");
else if (value < 0)
System.out.println("Path 2 is greater "
+ "than path 1");
else
System.out.println("Path 1 is greater "
+ "than path 2");
}
}
Java
// Java program to demonstrate
// Path.compareTo(Path) method
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class GFG {
public static void main(String[] args)
throws IOException
{
// create object of Paths
Path path1
= Paths.get("D:","eclipse","configuration","org.eclipse.update");
Path path2
= Paths.get("D:\\temp\\Spring");
// compare paths
int value = path1.compareTo(path2);
// print result
if (value == 0)
System.out.println("Both are equal");
else if (value < 0)
System.out.println("Path 2 is greater "
+ "than path 1");
else
System.out.println("Path 1 is greater "
+ "than path 2");
}
}
Both are equal
方案二:
Java
// Java program to demonstrate
// Path.compareTo(Path) method
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class GFG {
public static void main(String[] args)
throws IOException
{
// create object of Paths
Path path1
= Paths.get("D:","eclipse","configuration","org.eclipse.update");
Path path2
= Paths.get("D:\\temp\\Spring");
// compare paths
int value = path1.compareTo(path2);
// print result
if (value == 0)
System.out.println("Both are equal");
else if (value < 0)
System.out.println("Path 2 is greater "
+ "than path 1");
else
System.out.println("Path 1 is greater "
+ "than path 2");
}
}
Path 2 is greater than path 1
参考资料: https: Java Java.nio.file.Path)