Merge pull request #4029 from theawesomenayak/BAEL-1675

[BAEL-1675] Write to a File in Kotlin
This commit is contained in:
José Carlos Valero Sánchez 2018-05-05 14:13:49 +01:00 committed by GitHub
commit 2a61d6473b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 62 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.print(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,43 @@
package com.baeldung.filesystem
import org.junit.jupiter.api.Test
import java.io.File
import kotlin.test.assertEquals
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)
assertEquals(fileContent, File(fileName).readText())
}
@Test
fun whenWrittenWithBufferedWriter_thenCorrect() {
fileWriter.writeFileUsingBufferedWriter(fileName, fileContent)
assertEquals(fileContent, File(fileName).readText())
}
@Test
fun whenWrittenDirectly_thenCorrect() {
fileWriter.writeFileDirectly(fileName, fileContent)
assertEquals(fileContent, File(fileName).readText())
}
@Test
fun whenWrittenDirectlyAsBytes_thenCorrect() {
fileWriter.writeFileDirectlyAsBytes(fileName, fileContent)
assertEquals(fileContent, File(fileName).readText())
}
}