kotlin读取sd卡里的文件_如何在Kotlin中写入文件?
其他有趣的变化,因此您可以看到Kotlin的强大功能:通过创建字符串以一次全部写入的快速版本:File("somefile.txt").writeText(history.entries.joinToString("\n") { "${it.key}, ${it.value}" })// or just use the toString() method without transform:Fil
其他有趣的变化,因此您可以看到Kotlin的强大功能:
通过创建字符串以一次全部写入的快速版本:
File("somefile.txt").writeText(history.entries.joinToString("\n") { "${it.key}, ${it.value}" })
// or just use the toString() method without transform:
File("somefile.txt").writeText(x.entries.joinToString("\n"))
或者假设您可能会执行其他功能,例如过滤器行或仅使用前100条,等等。
File("somefile.txt").printWriter().use { out ->
history.map { "${it.key}, ${it.value}" }
.filter { ... }
.take(100)
.forEach { out.println(it) }
}
或给定一个toFile,允许通过创建扩展功能(类似于上面的toFile版本,但是流内容而不是首先实现一个大字符串),使用对字符串的转换将其写入文件中:
fun Iterable.toFile(output: File, transform: (T)->String = {it.toString()}) {
output.bufferedWriter().use { out ->
this.map(transform).forEach { out.write(it); out.newLine() }
}
}
fun Iterable.toFile(outputFilename: String, transform: (T)->String = {it.toString()}) {
this.toFile(File(outputFilename), transform)
}
用作以下任何一项:
history.entries.toFile(File("somefile.txt")) { "${it.key}, ${it.value}" }
history.entries.toFile("somefile.txt") { "${it.key}, ${it.value}" }
或在每个项目上使用默认的toString():
history.entries.toFile(File("somefile.txt"))
history.entries.toFile("somefile.txt")
或者给定一个toFile,通过创建以下扩展功能,允许从Iterable填充它:
fun File.fillWith(things: Iterable, transform: (T)->String = {it.toString()}) {
this.bufferedWriter().use { out ->
things.map(transform).forEach { out.write(it); out.newLine() }
}
}
使用方式:
File("somefile.txt").fillWith(history.entries) { "${it.key}, ${it.value}" }
或在每个项目上使用默认的toString():
File("somefile.txt").fillWith(history.entries)
如果您已经拥有另一个toFile扩展名,则可以重写,让一个扩展名调用另一个扩展名:
fun File.fillWith(things: Iterable, transform: (T)->String = {it.toString()}) {
things.toFile(this, transform)
}
更多推荐


所有评论(0)