Merge pull request #4029 from theawesomenayak/BAEL-1675
[BAEL-1675] Write to a File in Kotlin
This commit is contained in:
commit
2a61d6473b
|
@ -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())
|
||||
|
||||
}
|
|
@ -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())
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue