Scala 如何使用基本路径和相对路径构建路径?
假设我正在编写一个函数来构建一个给定基本路径和相对路径的文件路径,如下所示:Scala 如何使用基本路径和相对路径构建路径?,scala,file,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", "
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
我可以使用java.io.File
编写buildPath
:
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)
}
这个实现可以工作,但看起来很难看。你将如何改进它
新建java.io.File(“/”+basePath,relativePath)。getCanonicalPath
Afaik,“a/b/c/d/./e/x”是一个有效路径,所以我只需执行basePath+relativePath,就可以了!是的,“a/b/c/d/./e/x”是有效的,但我确实需要将其规范化(出于某些内部原因)。并不总是按要求工作<代码>新建java.io.File(“a/b/c/d”+”./e/x”).getCanonicalPath在我的例子中返回/Users/michael/a/b/c/d../e/x
。你的代码片段不是我建议的。。。仔细看:)它确实按要求工作。我的意思是我的代码可以。你的没有:)哦,对不起。现在我看到了。新的java.io.File(“a/b/c/d”,“e/x”)。getCanonicalPath
返回/Users/michael/a/b/c/e/x
,而不是a/b/c/e/x
。我错过什么了吗?