From c90ee1365668f180d98d8b83c91d3094e953276f Mon Sep 17 00:00:00 2001 From: Ilya Gorbunov Date: Mon, 21 Nov 2016 21:21:47 +0300 Subject: [PATCH] Performance: use byte array buffer directly to read the entire contents of a file. #KT-14883 Fixed --- libraries/stdlib/src/kotlin/io/FileReadWrite.kt | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/libraries/stdlib/src/kotlin/io/FileReadWrite.kt b/libraries/stdlib/src/kotlin/io/FileReadWrite.kt index e00acd97a23..5a0011ad0fd 100644 --- a/libraries/stdlib/src/kotlin/io/FileReadWrite.kt +++ b/libraries/stdlib/src/kotlin/io/FileReadWrite.kt @@ -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.