Path 常用方法介绍
Path 常用方法介绍
一、Path
1、路径构建
支持多级目录
当路径为相对路径时,构建的路径基于用于工作目录(System.getProperty("user.dir")
);当路径为绝对路径时,构建的路径为绝对路径
1 |
|
2、resolve
、resolveSibling
组合路径
this.resolve(other)
:other
可以为Path
也可以为字符路径
- 如果
other
是绝对路径,则结果就是other
- 如果
other
是相对路径,则结果为this + other
构成的路径1
2
3
4
5
6
7Path base = Paths.get("/home/path");
Path target = base.resolve("work");
输出:/home/path/work
Path base = Paths.get("/home/path");
Path target = base.resolve("/home/work");
输出:/home/work
this.resolveSibling(other)
:
解析指定路径的父路径产生其兄弟路径
- 如果
other
是绝对路径,则结果就是other
- 如果
other
是相对路径,则结果为this
的父路径拼接other
1
2
3
4
5
6
7Path base = Paths.get("/home/path");
Path target = base.resolveSibling("work");
输出:/home/work
Path base = Paths.get("/home/path");
Path target = base.resolveSibling("/home/work");
输出:/home/work
3、relativize
相对路径解析
相对于other
的路径,即有当前路径访问other
的相对路径
1 |
|
4、toAbsolutePath
转为绝对路径
生成的绝对路径可能会包含.
,..
例如基于relativize
生成的绝对路径为:/Users/user/Workspace/../user/work
5、normalize
路径格式化
移除路径中的.
,..
等冗余的路径元素
1 |
|
6、其他
getParent
:返回父路径或者nullgetFileName
:返回该路径的最后一个部件getRoot
:返回该路径的根路径
Path 常用方法介绍
https://probiecoder.cn/java/file.html