我想看看两条路径中的一条是否在另一条内部。
这到底是什么意思?我最初给出了两条路径,我想看看这两条路径中的一条是否指向另一条路径中的文件夹。
我认为最简单的方法如下:
path1.startsWith(path2) || path2.startsWith(path1)
这段代码是用 Kotling 编写的。
例子:
path1 = C:\Users\username\baeldung\bar
patht = C:\Users\username
这应该返回 true。如果我切换 path1 和 path2,结果也应该是 true。
现在我想到了这个问题,因为我正在比较路径,这些路径是否必须是规范的,如果是,我的比较方法是否仍然适用于规范路径?据我所知,两条路径都不使用
..
或 .
.因为我的程序应该在 Windows 和 Linux 机器上运行,不幸的是我不知道 Linux 机器上的路径与 Windows 路径有何不同。
最佳答案
为什么不直接使用 Path
类(class)?
/**
* True if [this] is parent of [other].
*/
fun Path.parentOf(other: Path?): Boolean {
return if (other == null) {
false
} else {
if (this == other) {
true
} else {
this.parentOf(other.parent)
}
}
}
/**
* True if one of the paths is inside the other.
*/
fun Path.oneInsideTheOther(other: Path): Boolean {
return this.parentOf(other) || other.parentOf(this)
}
fun main() {
val path1 = Paths.get("/Users/username/baeldung/bar")
val path2 = Paths.get("/Users/username")
println(path1)
println(path2)
println(path1.parentOf(path2))
println(path2.parentOf(path1))
println(path1.oneInsideTheOther(path2))
println(path1::class.java)
}
输出:
/Users/username/baeldung/bar
/Users/username
false
true
true
class sun.nio.fs.UnixPath
Path
接口(interface)在不同平台有不同的实现。我正在运行 Linux,所以我的实现是 JrtPath
, UnixPath
和 ZipPath
,但在 Windows 上,我想会有 WindowsPath
而不是 UnixPath
.因此,将特定于平台的字符串提供给 Paths.get()
您将获得特定于平台的 Path
实现,它是 parent
(此代码的关键)将按预期工作。
关于java - 比较路径 (Windows/Linux),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62391640/