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.
+16 -2
View File
@@ -41,7 +41,14 @@ class ReadWriteTest {
sample().forEachLine {
list.add(it)
}
assertEquals(arrayListOf("Hello", "World"), list)
assertEquals(listOf("Hello", "World"), list)
assertEquals(listOf("Hello", "World"), sample().readLines())
sample().useLines {
assertEquals(listOf("Hello", "World"), it.toList())
}
var reader = StringReader("")
var c = 0
@@ -78,10 +85,17 @@ class ReadWriteTest {
assertTrue(arr.contains('W'.toByte()))
}
val list = ArrayList<String>()
file.forEachLine("UTF8", {
file.forEachLine(Charsets.UTF_8, {
list.add(it)
})
assertEquals(arrayListOf("Hello", "World"), list)
assertEquals(arrayListOf("Hello", "World"), file.readLines())
file.useLines {
assertEquals(arrayListOf("Hello", "World"), it.toList())
}
val text = file.inputStream().reader().readText()
assertTrue(text.contains("Hello"))
assertTrue(text.contains("World"))