Java Path startsWith()方法及示例
java.nio.file.Path 的 startsWith() 方法用于检查这个路径对象是否以给定的路径或我们作为参数传递的字符串开始。
startsWith()方法有两种类型。
- java.nio.file.Path的startsWith(String other)方法用于检查这个路径是否以一个Path开始,这个Path是通过转换我们作为参数传递给这个方法的给定路径字符串构建的。例如,这个路径 “dir1/file1 “以 “dir1/file1 “和 “dir1 “开始。它没有以 “d “或 “dir “结束。
语法:
default boolean startsWith(String other)
参数:该方法接受一个参数其他,即给定的路径字符串。
返回值:如果这个路径以给定的路径开始,该方法返回true;否则返回false。
异常:如果路径字符串不能被转换为Path,该方法会抛出InvalidPathException。
下面的程序说明了 startsWith(String other) 方法。
程序 1:
// Java program to demonstrate// Path.startsWith(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("drive\\temp\\Spring"); // create a string object String passedPath = "drive"; // call startsWith() to check path object // starts with passedPath or not boolean check = path.startsWith(passedPath); // print result System.out.println("Path starts with \"" + passedPath + "\" :" + check); }}输出:
- java.nio.file.Path的startsWith(Path other)方法用于检查此路径是否以方法参数中的给定路径开始,如果此路径以给定路径开始,该方法返回true;否则返回false。
如果这个路径的根部分量与给定路径的根部分量相同,并且这个路径与给定路径的名称元素相同,那么这个路径就与给定路径开始。如果给定路径的名称元素比此路径多,则返回false。
这个路径的根部组件是否以给定路径的根部组件开始是针对文件系统的。如果这个路径没有根元素,而给定的路径有根元素,那么这个路径就不会从给定的路径开始。
如果给定路径与此路径的文件系统不同,则返回false。
语法:
boolean startsWith(Path other)
参数:该方法接受一个参数其他,即给定的路径。
返回值:如果这个路径以给定的路径开始,该方法返回真,否则返回假。
下面的程序说明了 startsWith(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 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 startsWith method to check functionality // of startsWith(Path other) method Path passedPath = Paths.get( "D:\\eclipse" + "\\plugins"); // call startsWith() to check path object // starts with passedPath or not boolean check = path.startsWith(passedPath); // print result System.out.println("Path starts with \" " + passedPath + "\" :" + check); }}输出:
参考资料
https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#startsWith(java.lang.String)https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#startsWith(java.nio.file.Path)