Skip to content

Support for File I/O handing in Kotlin multiplatform

Notifications You must be signed in to change notification settings

lamhoangx/LHFile_KMM

Repository files navigation

LHFile

Support for file handing in Kotlin multiplatform

File I/O handing for KMM

LHFile

expect class LHFile(path: String) {
    constructor(directory: String, fileName: String)
    val isDirectory: Boolean
    fun exists(): Boolean
    fun delete(): Boolean
    fun mkdirs()
    fun createNewFile()
}

Reader

expect class LHFileReader (path: String) {
    constructor(directory: String, fileName: String)
    fun isReady(): Boolean
    fun close()
    fun readLine(): String?
    fun getFilePointer(): Long
    fun seek(offset: Long)
}

Writer

expect class LHFileWriter (path: String) {
    constructor(directory: String, fileName: String)
    fun isReady(): Boolean
    fun close()
    fun write(data: String)
    fun writeBreakLine()
}

Test

// LHFileTest.kt
fun write(data: String) {
        val writer = LHFileWriter(path = pathFile)
        writer?.apply {
            if(isReady()) {
                LHTimber.d("WRITING...")
                for (i in 1..5) {
                    writer?.write("$i: $data")
                    writeBreakLine()
                }
            }
        }
        writer?.close()
    }

    fun read() {
        val reader = LHFileReader(path = pathFile)
        reader?.apply {
            if(isReady()) {
                var line: String? = null
                LHTimber.d("READING...")
                while (readLine()?.also { line = it } != null) {
                    line?.let {
                        LHTimber.d("LINE READ: $line")
                    }
                }
            }
        }
    }

Platform

// Android
val pathFile = "${baseContext.filesDir.absolutePath}/kmm_file_io.test"

LHFileTest(pathFile).apply {
    write("Hello world!")
    read()
}
// iOS
let pathDir = FileManager.default.urls(
    for: .documentDirectory,
    in: .userDomainMask
)[0]

let lhFile = LHFileTest(pathFile: "\(pathDir.path)/kmm_file_io.test")
lhFile.write(data: "Hello world!")
lhFile.read()

output


Happy coding __

Releases

No releases published

Packages

No packages published