1、前言
Path接口位于java.nio.file包中,所以Path接口的完全限定名称为java.nio.file.Path。Java Path实例表示文件系统中的路径。一个路径可以指向一个文件或一个目录。路径可以是绝对路径,也可以是相对路径。在许多方面,java.nio.file.Path接口类似于java.io.File类,但是有一些细微的差别。不过,在许多情况下,您可以使用Path接口来替换File类的使用。
2、Path 的使用
2.1 创建一个Path实例
可以使用Paths类(java.nio.file.Paths)中的静态方法来创建路径实例,名为Paths.get()。
public class PathExample { public static void main(String[] args) { Path path = Paths.get("D:dataestlog"); }}12345
2.2 API的使用
- static Path get(String first, String… more)
将给定的字符串拼接成路径
Path absolutePath = Paths.get("G:","data","est","log"); Path relativepath = Paths.get("test","log"); System.out.println("绝对路径是:"+absolutePath); System.out.println("相对路径是:"+relativepath);1234
控制台输出
绝对路径是:G:dataestlog相对路径是:testlog12
- Path resolve(Path other) 或 Path resolve(String other)
根据指定路径解析路径 若 other 是绝对路径,那么就返回 other ;否则,返回通过连接 this 和 other 获得的路径。
Path path1 = Paths.get("D:dataestlog"); System.out.println(path1.resolve("/log")); //D:log System.out.println(path1.resolve("./log")); //D:dataestlog.log System.out.println(path1.resolve("../log")); //D:dataestlog..log1234567
- Path resolveSibling(Path other) 或 Path resolveSibling(String other)
若 other 是绝对路径, 那么就返回 other ;否则,返回通过连接 this 的父路径和 other 获得的路径
Path path1 = Paths.get("D:dataestlog"); System.out.println(path1.resolveSibling("/log")); //D:log System.out.println(path1.resolveSibling("./log")); //D:dataest.log System.out.println(path1.resolveSibling("../log")); //D:dataest..log1234567
- toAbsolutePath()
返回与该路径等价的绝对路径
System.out.println(Paths.get("log","test").toAbsolutePath()); //G:IDEAplacemultithreadinglogest12
- relativize(Path other)
构造此路径和给定路径之间的相对路径。
Path path2 = Paths.get("D:dataestlogsjava.log"); System.out.println(path1.relativize(path2)); // ..logsjava.log123
- subpath(int beginIndex, int endIndex)
截取路径,包括第一个索引,不包括第二个索引
Path path = Paths.get("D:dataestlog");System.out.println(path.subpath(0, 2)); // dataest
![62dcda43a61734d1bec735e07872892e.gif](https://img-blog.csdnimg.cn/img_convert/62dcda43a61734d1bec735e07872892e.gif)