i want to list files of a Windows OS folder. I want to use Windows file addresses in Kotlin without using a double backslash. I do not want Kotlin to interpret the backslash here.
My best result for the moment you find at the end of my question.
Error: (3, 24) Kotlin: Illegal escape: '\ M' returns the following:
fun main(args: Array<String>) {
var s: String = "G:\My Web Sites\"
println(s)
}
I do not want to unmask the backslash with a backslash every time. I think it looks not good and can not easily copy back and forth.
works but is not pretty:
fun main(args: Array<String>) {
var s: String = "G:\\My Web Sites\\"
println(s)
}
walkaround:
Maybe I'll do it until I find another solution.
May there is a chance to switch the File.separator ?
of course this gaves me the same error, Because the replacement is too late:
import java.io.File
fun main(args: Array<String>) {
var s: String = "G:\My Web Sites\"
val replace = s.replace('/', File.separatorChar);
println(replace)
}
best result:
the best result i got is the following. it returns the correct file sting, but returns now files inside the folder. it returns the correct string: "G:\\My Web Sites\\"
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()
}