Support for file handing in Kotlin multiplatform
File I/O handing for KMM
expect class LHFile(path: String) {
constructor(directory: String, fileName: String)
val isDirectory: Boolean
fun exists(): Boolean
fun delete(): Boolean
fun mkdirs()
fun createNewFile()
}
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)
}
expect class LHFileWriter (path: String) {
constructor(directory: String, fileName: String)
fun isReady(): Boolean
fun close()
fun write(data: String)
fun writeBreakLine()
}
// 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()
Happy coding __