[BAEL-1675] Write to a File in Kotlin

This commit is contained in:
Siben Nayak 2018-04-03 15:28:38 +05:30
parent 323f5bf370
commit 5db1c3d8f3
2 changed files with 52 additions and 0 deletions

View File

@ -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())
}

View File

@ -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)
}
}