【问题标题】:Comparing paths (Windows/Linux)比较路径 (Windows/Linux)
【发布时间】:2020-10-05 01:36:12
【问题描述】:

我想看看两条路径中的一条是否在另一条路径中。

这到底是什么意思?我最初给出了两条路径,我想看看这两条路径中的一条是否指向另一条路径中的文件夹。

我认为最简单的方法如下:

path1.startsWith(path2) || path2.startsWith(path1)

这段代码是用 Kotling 编写的。

例子:

path1 = C:\Users\username\baeldung\bar
patht = C:\Users\username

这应该返回 true。如果我切换path1和path2,结果也应该是真的。

现在我想到了一个问题,因为我正在比较路径,这些路径是否必须是规范的,如果是,我的比较方法是否仍然适用于规范路径?据我所知,两条路径都不使用...

因为我的程序应该在 Windows 和 Linux 机器上运行,不幸的是我不知道 Linux 机器上的路径与 Windows 路径有何不同。

【问题讨论】:

  • 天真的解决方案是通过 path.separator 分割路径并比较结果数组,但需要注意的是您可能需要处理根部分。

标签: java linux windows kotlin path


【解决方案1】:

为什么不直接使用Path 类?

/**
 * 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 接口对不同平台有不同的实现。我正在运行 Linux,所以我的实现是 JrtPathUnixPathZipPath,但我猜在 Windows 上,会有 WindowsPath 而不是 UnixPath。因此,向Paths.get() 提供特定于平台的字符串,您将获得特定于平台的Path 实现,它的parent(此代码的关键)将按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 2021-06-27
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多