【问题标题】:list files of a Windows OS folder without using a double backslash file seperator在不使用双反斜杠文件分隔符的情况下列出 Windows 操作系统文件夹的文件
【发布时间】:2019-03-20 12:23:57
【问题描述】:

我想列出 Windows 操作系统文件夹的文件。 我想在 Kotlin 中使用 Windows 文件地址而不使用双反斜杠。 我不希望 Kotlin 在这里解释反斜杠。

你在我的问题结束时找到的最佳结果。

错误:(3, 24) Kotlin:非法转义:'\M' 返回以下内容:

fun main(args: Array<String>) {
    var s: String = "G:\My Web Sites\"
    println(s)
}

我不想每次都用反斜杠来掩盖反斜杠。我觉得它看起来不太好,不能轻易来回复制。

有效但不漂亮:

fun main(args: Array<String>) {
    var s: String = "G:\\My Web Sites\\"
    println(s)
}

绕行:

也许我会这样做,直到找到另一个解决方案。

可能有机会切换 File.separator 吗?

当然这给了我同样的错误,因为替换太晚了:

import java.io.File
fun main(args: Array<String>) {
    var s: String = "G:\My Web Sites\"
    val replace = s.replace('/', File.separatorChar);
    println(replace)
}

最佳结果:

我得到的最好结果如下。它返回正确的文件字符串,但现在返回文件夹内的文件。 它返回正确的字符串: "G:\\我的网站\\"

import java.io.File

fun main(args: Array<String>) {
    var s = """"G:\My Web Sites\"""
    println(s)
    s= s.replace("\\", "\\\\")
    println(s)
    File(s).walk().forEach  { println(it) }
}


private fun String.replace(regex: Regex, notMatched: (String) -> String, matched: (MatchResult) -> String): String {
//    its from https://github.com/http4k/http4k/blob/master/http4k-core/src/main/kotlin/org/http4k/core/UriTemplate.kt
    val matches = regex.findAll(this)
    val builder = StringBuilder()
    var position = 0
    for (matchResult in matches) {
        val before = substring(position, matchResult.range.start)
        if (before.isNotEmpty()) builder.append(notMatched(before))
        builder.append(matched(matchResult))
        position = matchResult.range.endInclusive + 1
    }
    val after = substring(position, length)
    if (after.isNotEmpty()) builder.append(notMatched(after))
    return builder.toString()
}

【问题讨论】:

    标签: kotlin


    【解决方案1】:

    您应该在代码中使用斜杠,JVM 会在 Windows 上自动将其转换为反斜杠(参见 Forward slash or backslash?)。

    如果您真的喜欢使用反斜杠,原始字符串 """ 可以完成这项工作,之后您无需手动替换它。

    【讨论】:

    猜你喜欢
    • 2018-12-21
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多