假设我正在编写一个函数,以给定像这样的基本路径和相对路径来构建文件路径:
def buildPath(basePath: String, relativePath: String) = ???
buildPath("a/b/c/d", "x") // a/b/c/x
buildPath("a/b/c/d", "../../x") // a/x
buildPath("a/b/c/d", "../../../x") // x
buildPath("a/b/c/d", "../e/x") // a/b/c/e/x
我可以使用buildPath
来写java.io.File
:
def buildPath(basePath: String, relativePath: String): String = {
val baseFile = new java.io.File(basePath)
val toRemove = baseFile.getAbsolutePath.dropRight(baseFile.getPath.length)
val file = new java.io.File(baseFile.getParentFile, relativePath)
file.getCanonicalPath.drop(toRemove.length)
}
此实现有效,但看起来很丑。您将如何改善它?
答案 0 :(得分:1)
new java.io.File("/" + basePath, relativePath).getCanonicalPath