ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
### [**Paths**的增减修改](https://lingcoder.gitee.io/onjava8/#/book/17-Files?id=paths%e7%9a%84%e5%a2%9e%e5%87%8f%e4%bf%ae%e6%94%b9) 我们必须能通过对**Path**对象增加或者删除一部分来构造一个新的**Path**对象。我们使用**relativize()**移除**Path**的根路径,使用**resolve()**添加**Path**的尾路径(不一定是“可发现”的名称)。 对于下面代码中的示例,我使用**relativize()**方法从所有的输出中移除根路径,部分原因是为了示范,部分原因是为了简化输出结果,这说明你可以使用该方法将绝对路径转为相对路径。 这个版本的代码中包含**id**,以便于跟踪输出结果: ~~~ // files/AddAndSubtractPaths.java import java.nio.file.*; import java.io.IOException; public class AddAndSubtractPaths { static Path base = Paths.get("..", "..", "..").toAbsolutePath().normalize(); static void show(int id, Path result) { if(result.isAbsolute()) System.out.println("(" + id + ")r " + base.relativize(result)); else System.out.println("(" + id + ") " + result); try { System.out.println("RealPath: " + result.toRealPath()); } catch(IOException e) { System.out.println(e); } } public static void main(String[] args) { System.out.println(System.getProperty("os.name")); System.out.println(base); Path p = Paths.get("AddAndSubtractPaths.java").toAbsolutePath(); show(1, p); Path convoluted = p.getParent().getParent() .resolve("strings").resolve("..") .resolve(p.getParent().getFileName()); show(2, convoluted); show(3, convoluted.normalize()); Path p2 = Paths.get("..", ".."); show(4, p2); show(5, p2.normalize()); show(6, p2.toAbsolutePath().normalize()); Path p3 = Paths.get(".").toAbsolutePath(); Path p4 = p3.resolve(p2); show(7, p4); show(8, p4.normalize()); Path p5 = Paths.get("").toAbsolutePath(); show(9, p5); show(10, p5.resolveSibling("strings")); show(11, Paths.get("nonexistent")); } } /* 输出: Windows 10 C:\Users\Bruce\Documents\GitHub (1)r onjava\ ExtractedExamples\files\AddAndSubtractPaths.java RealPath: C:\Users\Bruce\Documents\GitHub\onjava\ ExtractedExamples\files\AddAndSubtractPaths.java (2)r on-java\ExtractedExamples\strings\..\files RealPath: C:\Users\Bruce\Documents\GitHub\onjava\ ExtractedExamples\files (3)r on-java\ExtractedExamples\files RealPath: C:\Users\Bruce\Documents\GitHub\onjava\ ExtractedExamples\files (4) ..\.. RealPath: C:\Users\Bruce\Documents\GitHub\on-java (5) ..\.. RealPath: C:\Users\Bruce\Documents\GitHub\on-java (6)r on-java RealPath: C:\Users\Bruce\Documents\GitHub\on-java (7)r on-java\ExtractedExamples\files\.\..\.. RealPath: C:\Users\Bruce\Documents\GitHub\on-java (8)r on-java RealPath: C:\Users\Bruce\Documents\GitHub\on-java (9)r on-java\ExtractedExamples\files RealPath: C:\Users\Bruce\Documents\GitHub\onjava\ ExtractedExamples\files (10)r on-java\ExtractedExamples\strings RealPath: C:\Users\Bruce\Documents\GitHub\onjava\ ExtractedExamples\strings (11) nonexistent java.nio.file.NoSuchFileException: C:\Users\Bruce\Documents\GitHub\onjava\ ExtractedExamples\files\nonexistent */ ~~~ 我还为**toRealPath()**添加了更多的测试,这是为了扩展和规则化,防止路径不存在时抛出运行时异常。