在 kotlin native 中读/写文件 - IOS 端

Yes*_*day 6 android file ios kotlin kotlin-multiplatform


我想在 **IOS 端**创建文件并使用 Kotlin/Native 写入。

我有这个代码:

共同点:

expect class ReadWriteFile
Run Code Online (Sandbox Code Playgroud)

在 androidMain 中:

actual class ReadWriteFile {
    fun read(path : String, filename: String) : Boolean {
        val file = File("$path/$filename")
        return if(file.exists()) {
            file.forEachLine {
                // do something
            }
            true
        } else {
            false
        }
    }

    fun save(path : String, filename : String, nbLine : Int) {
        val file = File("$path/$filename")
        val w = file.writer()
        for(it in 1..nbLine) {
            w.write("write something\n")
        }
        w.close()
    }
}

Run Code Online (Sandbox Code Playgroud)

在 iosMain 中:

actual class ReadWriteFile {
    fun read(path : String, filename: String) : Boolean {
        ???????????
    }

    fun save(path : String, filename : String, nbLine : Int) {
        ???????????
    }
}
Run Code Online (Sandbox Code Playgroud)

Phi*_*hov 6

尝试这样的事情:

import platform.Foundation.*

class ReadWriteFile {
    fun read(path : String, filename: String) : Boolean {
        val string = NSString.stringWithContentsOfFile(path, NSUTF8StringEncoding, null) ?: return false
        string.lines().forEach {
            println(it)
        }
        return true
    }

    fun save(path : String, filename : String, nbLine : Int) {
        val result = (1..nbLine).map {
            "string $it"
        }
        (result as NSString).writeToFile(path, true, NSUTF8StringEncoding, null)
    }
}
Run Code Online (Sandbox Code Playgroud)

一般来说,如果您需要找到一个本机解决方案,那么搜索 Obj-C 解决方案会更容易 - 因为 kotlin 会转换为它,而不是 Swift,然后或import platform.Foundation.*根据import platform.UIKit.*使用的类并采用 kotlin。