Java Path resolveSibling()方法及示例

来源:这里教程网 时间:2026-02-17 21:04:45 作者:

Java Path resolveSibling()方法及示例

java.nio.file.PathresolveSibling() 方法用于将给定的路径与该路径的父路径进行解析。

有两种类型的resolveSibling()方法。

    resolveSibling(Path other)方法java.nio.file.Path用于将给定路径作为参数与该路径的父路径进行解析。这在一个文件名需要被替换成另一个文件名时非常有用。例如,假设名字的分隔符是”/”,路径代表 “drive/newFile/spring”,那么用Path “plugin “来调用这个方法将得到Path “drive/newFile/plugin”。如果这个路径没有一个父路径或者其他是绝对的,那么这个方法就会返回其他。如果其他路径是空的,那么这个方法就会返回这个路径的父路径,或者在这个路径没有父路径的情况下,返回空路径。

语法:

default Path resolveSibling(Path other)

参数:该方法接受一个参数其他,即要对该路径的父级进行解析的路径。

返回值:该方法返回结果路径。

下面的程序说明了 resolveSibling(Path other) 方法。

程序 1:

// Java program to demonstrate// Path.resolveSibling(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("drive\\temp\\Spring");          // create an object of Path        // to pass to resolve method        Path path2            = Paths.get("programs\\workspace");          // call resolveSibling()        // to create resolved Path        // on parent of path object        Path resolvedPath            = path.resolveSibling(path2);          // print result        System.out.println("Resolved Path "                           + "of path's parent:"                           + resolvedPath);    }}

输出:

    java.nio.file.Path的resolveSibling(String other)方法用于将我们作为参数传递的给定路径字符串转换为一个Path,并以与solveSibling方法所指定的完全相同的方式对该路径的父路径进行解析。

语法:

default Path resolveSibling(String other)

参数:该方法接受一个参数其他,即要对该路径的父级进行解析的路径字符串。

返回值:该方法返回结果路径。

异常:如果路径字符串不能被转换为Path,该方法会抛出InvalidPathException

下面的程序说明了resolveSibling(String other)方法。

程序 1:

// Java program to demonstrate// Path.resolveSibling(String 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("drive\\temp\\Spring");          // create a string object        String passedPath = "drive";          // call resolveSibling()        // to create resolved Path        // on parent of path object        Path resolvedPath            = path.resolveSibling(passedPath);          // print result        System.out.println("Resolved Path of "                           + "path's parent:"                           + resolvedPath);    }}

输出:

参考资料

https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#resolveSibling(java.lang.String)https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#resolveSibling(java.nio.file.Path)

相关推荐