Avoid allocating large buffers in File.writeText #KT-51058

Also fixes File.appendText and Path.write/appendText.


Merge-request: KT-MR-12804
Merged-by: Abduqodiri Qurbonzoda <abduqodiri.qurbonzoda@jetbrains.com>
This commit is contained in:
Abduqodiri Qurbonzoda
2023-11-08 11:18:56 +00:00
committed by Space Team
parent 54ab3d39db
commit 999b0f7099
3 changed files with 191 additions and 5 deletions
@@ -10,6 +10,7 @@
package kotlin.io.path
import java.io.*
import java.nio.CharBuffer
import java.nio.charset.Charset
import java.nio.file.Files
import java.nio.file.OpenOption
@@ -168,7 +169,22 @@ public fun Path.readText(charset: Charset = Charsets.UTF_8): String =
@WasExperimental(ExperimentalPathApi::class)
@Throws(IOException::class)
public fun Path.writeText(text: CharSequence, charset: Charset = Charsets.UTF_8, vararg options: OpenOption) {
Files.newOutputStream(this, *options).writer(charset).use { it.append(text) }
Files.newOutputStream(this, *options).use { out ->
if (text is String) {
out.writeTextImpl(text, charset)
return@use
}
val encoder = charset.newReplaceEncoder()
val charBuffer = if (text is CharBuffer) text.asReadOnlyBuffer() else CharBuffer.wrap(text)
val byteBuffer = byteBufferForEncoding(chunkSize = minOf(text.length, DEFAULT_BUFFER_SIZE), encoder)
while (charBuffer.hasRemaining()) {
encoder.encode(charBuffer, byteBuffer, /*endOfInput = */true).also { check(!it.isError) }
out.write(byteBuffer.array(), 0, byteBuffer.position())
byteBuffer.clear()
}
}
}
/**
@@ -181,7 +197,7 @@ public fun Path.writeText(text: CharSequence, charset: Charset = Charsets.UTF_8,
@WasExperimental(ExperimentalPathApi::class)
@Throws(IOException::class)
public fun Path.appendText(text: CharSequence, charset: Charset = Charsets.UTF_8) {
Files.newOutputStream(this, StandardOpenOption.APPEND).writer(charset).use { it.append(text) }
writeText(text, charset, StandardOpenOption.APPEND)
}
/**