Performance: use byte array buffer directly to read the entire contents of a file.

#KT-14883 Fixed
This commit is contained in:
Ilya Gorbunov
2016-11-21 21:21:47 +03:00
parent 5eaa23ec60
commit c90ee13656
@@ -49,7 +49,18 @@ public inline fun File.printWriter(charset: Charset = Charsets.UTF_8): PrintWrit
*
* @return the entire content of this file as a byte array.
*/
public fun File.readBytes(): ByteArray = FileInputStream(this).use { it.readBytes(length().toInt()) }
public fun File.readBytes(): ByteArray = FileInputStream(this).use { input ->
var offset = 0
var remaining = this.length().toInt() // TODO: toIntExact()
val result = ByteArray(remaining)
while (remaining > 0) {
val read = input.read(result, offset, remaining)
if (read < 0) break
remaining -= read
offset += read
}
if (remaining == 0) result else result.copyOf(offset)
}
/**
* Sets the content of this file as an [array] of bytes.