如何使用基本路径和相对路径构建路径?

时间:2019-03-19 16:24:41

标签: scala file

假设我正在编写一个函数,以给定像这样的基本路径和相对路径来构建文件路径:

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)
}

此实现有效,但看起来很丑。您将如何改善它?

1 个答案:

答案 0 :(得分:1)

new java.io.File("/" + basePath, relativePath).getCanonicalPath