Kotlin Files Paths write ByteArray writeString写多行BufferedWriter
Kotlin
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardOpenOption
fun main(args: Array<String>) {
val filePath = "./myfile.txt"
val path = Paths.get(filePath)
val bytes: ByteArray = "hello,".toByteArray() //覆盖写文件
Files.write(path, bytes)
val string: String = "world!"
Files.writeString(path, string, StandardOpenOption.APPEND) //原文件追加
val bufferedWriter = Files.newBufferedWriter(path, StandardOpenOption.APPEND)
bufferedWriter.newLine() //换行
bufferedWriter.flush()
var lines = mutableListOf<String>()
repeat(3) {
lines.add(it.toString())
}
Files.write(path, lines, StandardOpenOption.APPEND) //写入多行
bufferedWriter.write("2023")
bufferedWriter.flush() //预备写的数据在内存,flush流,写入本地。
bufferedWriter.close()
//打印文件全部内容
println(Files.readString(path))
}
hello,world!
0
1
2
2023