File.useLines and Reader.readLines.

This commit is contained in:
Ilya Gorbunov
2016-01-06 04:21:56 +03:00
parent ddcafdd9b3
commit d64882e19b
3 changed files with 38 additions and 4 deletions
@@ -207,11 +207,11 @@ public fun File.outputStream(): FileOutputStream {
}
/**
* Reads the file content as a list of lines. By default uses UTF-8 charset.
* Reads the file content as a list of lines.
*
* Do not use this function for huge files.
*
* @param charset character set to use.
* @param charset character set to use. By default uses UTF-8 charset.
* @return list of file lines.
*/
public fun File.readLines(charset: Charset = Charsets.UTF_8): List<String> {
@@ -220,3 +220,12 @@ public fun File.readLines(charset: Charset = Charsets.UTF_8): List<String> {
return result
}
/**
* Calls the [block] callback giving it a sequence of all the lines in this file and closes the reader once
* the processing is complete.
* @param charset character set to use. By default uses UTF-8 charset.
* @return the value returned by [block].
*/
public inline fun <T> File.useLines(charset: Charset = Charsets.UTF_8, block: (Sequence<String>) -> T): T =
bufferedReader(charset).use { block(it.lineSequence()) }
@@ -24,6 +24,17 @@ public fun Writer.buffered(bufferSize: Int = defaultBufferSize): BufferedWriter
*/
public fun Reader.forEachLine(block: (String) -> Unit): Unit = useLines { it.forEach(block) }
/**
* Reads this reader content as a list of lines.
*
* Do not use this function for huge files.
*/
public fun Reader.readLines(): List<String> {
val result = arrayListOf<String>()
forEachLine { result.add(it) }
return result
}
/**
* Calls the [block] callback giving it a sequence of all the lines in this file and closes the reader once
* the processing is complete.