java - 替换 Java 路径的第一部分
问题描述
在 Java 中,我正在寻找一种解决方案,用另一个路径替换路径的第一部分。
我找到的唯一解决方案有点难看,你可以在subPath
下面的方法中找到它:
import java.nio.file.Path;
import java.nio.file.Paths;
public class TestPath {
static Path subPath(Path newPrefix, Path pathWithOldPrefix){ ;
Path result;
if(pathWithOldPrefix.getNameCount() > 1) {
result = newPrefix.resolve(pathWithOldPrefix.subpath(1, pathWithOldPrefix.getNameCount()));
}else{
result = newPrefix;
}
return result;
}
public static void main(String[] args) {
//display "/newPrefix/myPath"
System.out.println(subPath(Paths.get("/newPrefix"), Paths.get("/oldPrefix/myPath")));
//display "/newPrefix
System.out.println(subPath(Paths.get("/newPrefix"), Paths.get("/oldPrefix/")));
}
}
有什么更好的解决方案吗?
解决方案
Path pathWithOldPrefix = Paths.get("/oldPrefix/myPath");
Path oldPrefix = Paths.get("/oldPrefix"); // Or maybe
Path oldPrefix = pathWithOldPrefix.subpath(0, 1);
Path newPrefix = Paths.get("/newPrefix");
Path relative = oldPrefix.relativize(pathWithOldPrefix); // myPath
Path newPath = newPrefix.resolve(relative); // /newPrefix/myPath
Path newPath2 = newPrefix.resolve(oldPrefix.relativize(pathWithOldPrefix));
// /newPrefix/myPath
所以relativize
删除了 oldPrefix (注意参数的顺序)。然后resolve
添加到前缀。
推荐阅读
- mathematical-optimization - 澄清 SCIP“显示问题”和“写入统计信息”命令中使用的术语
- javascript - 如何使用两个参数进行完全匹配搜索?
- javascript - npm install 失败,弃用 core.js
- powershell - 如何将追加添加到我的 powershell 脚本?
- apache-kafka - 哪些消息应该发布到 Kafka 主题,何时发布?
- c++ - g++ 和 clang++ 与 enable_if 的区别
- php - 如何将编码从 utf8 更改为大端
- c++ - 多个线程同时在同一向量的不同向量上添加元素发生错误
- javascript - 如何使用 RxJS 来协调串行和并行作业?
- javascript - Jquery在包装每个x元素时追加