Kotlin

    技术2024-01-21  94

    读写文件操作记录, 提取成函数,方便看其返回值,以加深理解。

    private fun createNewFile(): File { var file = File("output.txt") if (file.exists()) { file.delete() } file.createNewFile() return file } private fun readLineFromFile(filePath: String): List<String> { val file = File(filePath) return file.readLines() } private fun readTextFromFile(filePath: String): String { val file = File(filePath) return file.readText() } private fun writeTextToFile(file: File, text : String, isNeedChangeLine : Boolean) { var strContent = text if (isNeedChangeLine) { strContent += "\r\n" } var randomAccessFile = RandomAccessFile(file, "rwd") randomAccessFile.seek(file.length()) randomAccessFile.write(strContent.toByteArray()) randomAccessFile.close() } }

    其中 readLines() 是按行读取,readText 是直接读取文本所有内容

    写入文件借助RandomAccessFile 类,并处理换行输入 (File.writeText 是会直接覆盖文本之前的内容的)

    Processed: 0.009, SQL: 9