From a34a6b71c1ca3279894c4e8037235f57bf149b31 Mon Sep 17 00:00:00 2001 From: Ekaterina Sosa Date: Tue, 9 Apr 2013 00:56:44 +0400 Subject: [PATCH] KT-3376 Added appendText and appendBytes functions to kotlin.io.File #KT-3375 fixed --- libraries/stdlib/src/kotlin/io/Files.kt | 24 ++++++++++++++++++++++++ libraries/stdlib/test/IoTest.kt | 10 ++++++++++ 2 files changed, 34 insertions(+) diff --git a/libraries/stdlib/src/kotlin/io/Files.kt b/libraries/stdlib/src/kotlin/io/Files.kt index 6061e0d2201..0f48ec9bff7 100644 --- a/libraries/stdlib/src/kotlin/io/Files.kt +++ b/libraries/stdlib/src/kotlin/io/Files.kt @@ -101,6 +101,14 @@ public fun File.readBytes(): ByteArray { public fun File.writeBytes(data: ByteArray): Unit { return FileOutputStream(this).use{ it.write(data) } } + +/** + * Appends bytes to the contents of the file. + */ +public fun File.appendBytes(data: ByteArray): Unit { + return FileOutputStream(this, true).use{ it.write(data) } +} + /** * Reads the entire content of the file as a String using the optional * character encoding. The default platform encoding is used if the character @@ -132,6 +140,22 @@ public fun File.writeText(text: String, encoding:String?=null): Unit { writeByte */ public fun File.writeText(text: String, encoding:Charset): Unit { writeBytes(text.toByteArray(encoding)) } +/** + * Appends text to the contents of the file using a given character encoding. + */ +public fun File.appendText(text: String, encoding: Charset): Unit { + appendBytes(text.toByteArray(encoding)) +} + +/** + * Appends text to the contents of the file using optional character encoding. + * The default platform encoding is used if the character encoding is + * not specified or null. + */ +public fun File.appendText(text: String, encoding: String? = null): Unit { + appendBytes(text.toByteArray(encoding)) +} + /** * Copies this file to the given output file, returning the number of bytes copied */ diff --git a/libraries/stdlib/test/IoTest.kt b/libraries/stdlib/test/IoTest.kt index 57ca3b9d8a1..eddeee0a91a 100644 --- a/libraries/stdlib/test/IoTest.kt +++ b/libraries/stdlib/test/IoTest.kt @@ -137,4 +137,14 @@ class IoTest(){ assertEquals(4, totalFilesWithUnReadableDir) } } + + test fun testAppendText() { + val file = File.createTempFile("temp", System.nanoTime().toString()) + file.writeText("Hello\n") + file.appendText("World") + + assertEquals("Hello\nWorld", file.readText()) + file.deleteOnExit() + } + }