Java中的路径 equals() 方法及示例
Java Path 接口是在Java 7 中添加到Java NIO 中的。Path 接口位于Java.nio.file 包中,因此Java Path 接口的全称是Java.nio.file.Path。 Java Path 实例表示文件系统中的路径。路径可以用来定位文件或目录。实体的路径可以有两种类型,一种是绝对路径,另一种是相对路径。绝对路径是从根到实体的位置地址,而相对路径是相对于其他路径的位置地址。
Java.nio.file.Path的equals()方法用于将此路径与作为参数传递的对象进行比较是否相等。如果给定对象不是 Path 或者是与不同 FileSystem 关联的 Path,则此方法返回 false。当且仅当给定对象是与此路径相同的路径时,此方法才返回 true。
句法:
boolean equals(Object other)
参数:此方法接受用于比较的另一个对象的单个参数。
返回值:当且仅当给定对象是与此路径相同的路径时,此方法返回 true。
下面的程序说明了 equals() 方法:
方案一:
// Java program to demonstrate
// java.nio.file.Path.equals() 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 for equality
boolean response
= path1.equals(path2);
// print result
if (response)
System.out.println("Both are equal");
else
System.out.println("Both are not equal");
}
}
输出:
Both are equal
方案二:
// Java program to demonstrate
// java.nio.file.Path.equals() 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 for equality
boolean response = path1.equals(path2);
// print result
if (response)
System.out.println("Both are equal");
else
System.out.println("Both are not equal");
}
}
输出:
Both are not equal
参考资料: https: Java/nio/file/Path.html#equals()