java - 比较路径 (Windows/Linux)

标签 java linux windows kotlin path

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

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

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

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 , UnixPathZipPath ,但在 Windows 上,我想会有 WindowsPath而不是 UnixPath .因此,将特定于平台的字符串提供给 Paths.get()您将获得特定于平台的 Path实现,它是 parent (此代码的关键)将按预期工作。

关于java - 比较路径 (Windows/Linux),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62391640/

相关文章:

java - 如何修改Jenkins官方Docker镜像中的Java内存?

java - 是否可以将 Jbehave 与 testNG 集成?

windows - Cassandra 不是从 cassandra -f 开始的

windows - 错误无效的 Windows 安装类型 : 'bind' on Windows 10 docker build of Windows container

java - 在 java : lookbehind with specified length 中拆分字符串

java - 我可以通过检查主 Activity 的 onPause() 中的 isFinish() 来确定 Android 应用程序完成运行吗?

linux - 有人可以帮我将每小时和每天的日志文件分成一个单独的文件吗?

python - 树莓派和 Pusher

linux - 仅在 shell 脚本中一小时后提取数据

c++ - DirectShow 视频剪辑