[BAEL-1675] Write to a File in Kotlin
This commit is contained in:
parent
323f5bf370
commit
5db1c3d8f3
|
@ -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())
|
||||||
|
|
||||||
|
}
|
|
@ -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)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in New Issue