给定以下传入路径,例如
C:\cresttest\parent_3\child_3_1\child_3_1_.txt
如何在上述路径之间更新和添加新目录以构建以下结果
C:\cresttest\NEW_PATH\parent_3\child_3_1\child_3_1_.txt
目前我正在使用多个子字符串来识别传入路径,但传入路径是随机和动态的。使用子字符串并放置我的新路径需要更多代码行或不必要的处理,是否有任何 API 或方法可以轻松地在绝对路径之间更新和添加我的新目录?
最佳答案
通过使用 java.nio.file.Path ,您可以执行以下操作:
Path incomingPath = Paths.get("C:\\cresttest\\parent_3\\child_3_1\\child_3_1_.txt");
//getting C:\cresttest\, adding NEW_PATH to it
Path subPathWithAddition = incomingPath.subpath(0, 2).resolve("NEW_PATH");
//Concatenating C:\cresttest\NEW_PATH\ with \parent_3\child_3_1\child_3_1_.txt
Path finalPath = subPathWithAddition.resolve(incomingPath.subpath(2, incomingPath.getNameCount()));
然后您可以通过调用 finalPath.toUri()
注意:这不依赖于路径中的任何名称,但它取决于目录深度,您可以在 subpath
调用中对其进行编辑。
注意 2:您可以将创建的 Path
实例数量减少为一个,我创建了三个以提高可读性。
关于java - 如何动态更新绝对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34287712/