Java Path resolve()方法及实例
java.nio.file.Path 的 resolve() 方法用于解决给定的路径与这个路径的关系。
有两种类型的resolve()方法。
- resolve(String other)方法是java.nio.file.Path的方法,用于将给定的路径字符串转换为Path,并以与resolve方法所指定的完全相同的方式对该路径进行解析。例如,如果名称分隔符是”/”,并且路径代表 “c/drive/files”,那么用路径字符串 “file1 “来调用这个方法将导致路径 “c/drive/files/file1″。
语法:
default Path resolve(String other)
参数:该方法接受一个参数其他,即针对该路径解析的路径字符串。
返回值:该方法返回结果路径。
异常:如果路径字符串不能被转换为Path,该方法会抛出InvalidPathException。
下面的程序说明了resolve(String other)方法。
程序 1:
// Java program to demonstrate // Path.resolve(String other) method import java.nio.file.*; public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get("drive\\temp\\Spring"); // create a string object String passedPath = "drive"; // call resolve() to create resolved Path Path resolvedPath = path.resolve(passedPath); // print result System.out.println("Resolved Path:" + resolvedPath); } }输出:
- resolve(Path other)方法java.nio.file.Path用来解决给定的路径与这个路径的问题。如果这个路径是 “C/temp”,而传递的路径是 “drive/newFile”,那么这个方法将在这个路径的末尾加上传递的路径,并使用”/”作为分隔符。所以解决的路径将是 “C/temp/drive/newFile”。
如果其他参数是一个绝对路径,那么这个方法就会简单地返回其他。如果其他参数是一个空的路径,那么这个方法就简单地返回这个路径。否则,这个方法认为这个路径是一个目录,并根据这个路径解析给定的路径。在最简单的情况下,给定的路径没有根部分,在这种情况下,这个方法将给定的路径与这个路径连接起来,并返回一个以给定路径为终点的结果路径。如果给定的路径有一个根部分,那么解决方法就与实现有很大的关系,因此没有具体说明。
语法:
Path resolve(Path other)
参数:该方法接受一个单一的参数其他,它是针对该路径的解析路径。
返回值:该方法返回结果路径。
下面的程序说明了resolve(Path other)方法。
程序 1:
// Java program to demonstrate// Path.resolve(Path other) method import java.nio.file.*; public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get("drive\\temp\\Spring"); // create an object of Path // to pass to resolve method Path path2 = Paths.get("programs\\workspace"); // call resolve() // to create resolved Path Path resolvedPath = path.resolve(path2); // print result System.out.println("Resolved Path:" + resolvedPath); }}输出:
参考资料
https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#resolve(java.lang.String)https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#resolve(java.nio.file.Path)