From 5db1c3d8f352ba308ffcab29cba8a11ce2f8e4a3 Mon Sep 17 00:00:00 2001 From: Siben Nayak Date: Tue, 3 Apr 2018 15:28:38 +0530 Subject: [PATCH] [BAEL-1675] Write to a File in Kotlin --- .../com/baeldung/filesystem/FileWriter.kt | 19 +++++++++++ .../com/baeldung/filesystem/FileWriterTest.kt | 33 +++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/filesystem/FileWriter.kt create mode 100644 core-kotlin/src/test/kotlin/com/baeldung/filesystem/FileWriterTest.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/filesystem/FileWriter.kt b/core-kotlin/src/main/kotlin/com/baeldung/filesystem/FileWriter.kt new file mode 100644 index 0000000000..20d9c963c7 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/filesystem/FileWriter.kt @@ -0,0 +1,19 @@ +package com.baeldung.filesystem + +import java.io.File + +class FileWriter { + + fun writeFileUsingPrintWriter(fileName: String, fileContent: String) = + File(fileName).printWriter().use { out -> out.println(fileContent) } + + fun writeFileUsingBufferedWriter(fileName: String, fileContent: String) = + File(fileName).bufferedWriter().use { out -> out.write(fileContent) } + + fun writeFileDirectly(fileName: String, fileContent: String) = + File(fileName).writeText(fileContent) + + fun writeFileDirectlyAsBytes(fileName: String, fileContent: String) = + File(fileName).writeBytes(fileContent.toByteArray()) + +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/filesystem/FileWriterTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/filesystem/FileWriterTest.kt new file mode 100644 index 0000000000..43a9957de1 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/filesystem/FileWriterTest.kt @@ -0,0 +1,33 @@ +package com.baeldung.filesystem + +import org.junit.jupiter.api.Test + +internal class FileWriterTest { + + private val fileName = "src/test/resources/Kotlin.out" + + private val fileContent = "Kotlin\nConcise, Safe, Interoperable, Tool-friendly" + + private val fileWriter = FileWriter() + + @Test + fun whenWrittenWithPrintWriter_thenCorrect() { + fileWriter.writeFileUsingPrintWriter(fileName, fileContent) + } + + @Test + fun whenWrittenWithBufferedWriter_thenCorrect() { + fileWriter.writeFileUsingBufferedWriter(fileName, fileContent) + } + + @Test + fun whenWrittenDirectly_thenCorrect() { + fileWriter.writeFileDirectly(fileName, fileContent) + } + + @Test + fun whenWrittenDirectlyAsBytes_thenCorrect() { + fileWriter.writeFileDirectlyAsBytes(fileName, fileContent) + } + +} \ No newline at end of file