Java Path endsWith()方法及实例
java.nio.file.Path 的 endswith() 方法用于检查这个路径对象是否以给定的路径或我们作为参数传递的字符串结束。
endsWith()方法有两种类型。
- java.nio.file.Path的endsWith(String other)方法用于检查这个路径是否以一个Path结束,这个Path是通过转换我们作为参数传递给这个方法的给定路径字符串构建的。例如,这个路径 “dir1/file1 “以 “dir1/file1 “和 “file1 “结束。它没有以 “1 “或”/file1 “结尾。请注意,尾部的分隔符没有被考虑在内,所以在Path “dir1/file1 “上调用这个方法时,字符串 “file1/”会返回true。
语法:
default boolean endsWith(String other)
参数:该方法接受一个参数其他,即给定的路径字符串。
返回值:如果这个路径以给定的路径结束,该方法返回真,否则返回假。
异常:如果路径字符串不能被转换为Path,该方法会抛出InvalidPathException。
下面的程序说明了 endsWith(String other) 方法。
程序 1:
// Java program to demonstrate// Path.endsWith(String other) method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get("\\temp\\Spring"); // create a string object String passedPath = "Spring"; // call endsWith() to check path object // ends with passedPath or not boolean check = path.endsWith(passedPath); // print result System.out.println("Path ends with " + passedPath + " :" + check); }}输出:
- java.nio.file.Path的endsWith(Path other)方法用于检查此路径是否以方法参数中的给定路径结束。如果此路径以给定路径结束,该方法返回true;否则返回false。
如果传递的路径有N个元素,并且没有根元素,而这个路径有N个或更多的元素,那么如果每个路径的最后N个元素,从离根最远的元素开始,都相等,那么这个路径就以给定的路径结束。
如果通过的路径有一个根部分量,那么如果这个路径的根部分量与给定路径的根部分量结束,并且两个路径的相应元素都相等,那么这个路径就与给定路径结束。这个路径的根部分是否与给定路径的根部分结束是由文件系统决定的。如果这个路径没有根部组件,而给定的路径有根部组件,那么这个路径就不会与给定的路径结束。
如果给定路径与此路径的文件系统不同,则返回false。
语法:
boolean endsWith(Path other)
参数:该方法接受一个参数其他,即给定的路径。
返回值:如果这个路径与给定的路径结束,该方法返回真,否则返回假。
下面的程序说明了endsWith(Path other)方法。
程序 1:
// Java program to demonstrate// java.nio.file.Path.(Path other) method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get("D:\\eclipse" + "\\plugins" + "\\javax.xml.rpc_1.1.0.v201209140446" + "\\lib"); // create a path object which we will pass // to endsWith method to check functionality // of endsWith(Path other) method Path passedPath = Paths.get( "javax.xml.rpc_1.1.0.v201209140446" + "\\lib"); // call endsWith() to check path object // ends with passedPath or not boolean check = path.endsWith(passedPath); // print result System.out.println("Path ends with " + passedPath + " :" + check); }}输出:
参考资料
https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#endsWith(java.lang.String)https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#endsWith(java.nio.file.Path)