问题描述
如何为 Kotlin Native/iOS 正确实现这些功能?我正在尝试为 DFU 实用程序实现文件读取,但它不起作用。
iOS 实现:
actual class PlatformFile actual constructor(val filePath: String) {
private val platformFile = NSFileHandle.fileHandleForReadingAtPath(filePath)
actual fun setPosition(start: Long) {
platformFile!!.seekToFileOffset(start.toULong())
}
actual fun getLength(): Long {
val fileSize = NSFileManager.defaultManager.attributesOfItemAtPath(filePath,null) as NSDictionary
return fileSize.fileSize().toLong()
}
actual fun readIntoBuffer(buffer: ByteArray): Int {
val read = platformFile!!.readDataOfLength(buffer.size.toULong())
buffer = read.toByteArray()
return read.length.toInt()
}
}
常见实现:
expect class PlatformFile(filePath: String) {
/**
* Sets the file-pointer offset,measured from the beginning of this
* file,at which the next read or write occurs.
*/
fun setPosition(start: Long)
fun getLength(): Long
/**
* Reads up to {@code buffer.length} bytes of data from this file
* into an array of bytes.
* @param buffer the buffer into which the data is read.
* @return the total number of bytes read into the buffer,or
* {@code -1} if there is no more data because the end of
* this file has been reached.
*/
fun readIntoBuffer(buffer: ByteArray): Int
}
Android 实现(工作实现):
import java.io.RandomAccessFile
actual class PlatformFile actual constructor(filePath: String) {
private val platformFile = RandomAccessFile(filePath,"r")
actual fun setPosition(start: Long) = platformFile.seek(start)
actual fun getLength(): Long = platformFile.length()
actual fun readIntoBuffer(buffer: ByteArray): Int = platformFile.read(buffer)
}
解决方法
它究竟是如何不起作用的?编译器错误、运行时错误,或者根本没有按照您的预期运行?错误消息/堆栈跟踪会有所帮助。
另外,您是否考虑过使用 Okio?它部分是多平台的,包括文件系统部分。