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

标签 android ios file kotlin kotlin-multiplatform

我想在 **IOS 端**创建文件并使用 Kotlin/Native 写入。
我有这个代码:
共同点:

expect class ReadWriteFile
在 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()
    }
}

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

    fun save(path : String, filename : String, nbLine : Int) {
        ???????????
    }
}

最佳答案

尝试这样的事情:

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)
    }
}
一般来说,如果您需要找到原生解决方案,搜索 Obj-C 解决方案更容易——因为 kotlin 被转换为它,而不是 Swift,然后 import platform.Foundation.*import platform.UIKit.*取决于使用的类并采用 kotlin。

关于android - 在 kotlin native 中读/写文件 - IOS 端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61078285/

相关文章:

iphone - 如何用颜色填充形状

java - 将日志文件拆分为由正则表达式分隔的 block

复制文本文件的内容并将其复制到另一个文件

python - python 从不同目录下的多个文件中读取特定数据

android - 如何解决非 Activity InputConnection 上的 showStatusIcon

java - 关闭网络连接时显示先前加载的数据的技术

java - ListFragment 更改尺寸

ios - 在 swift 2.0 iOS 中使用 peek 和 pop 时如何更改模糊 View 的背景颜色

ios - 使用 KFEpubKit 的 KissXML pod 问题

android - android studio中png图像的白色背景