Merge pull request #3912 from theawesomenayak/BAEL-1676

[BAEL-1676] Kotlin Read from File
This commit is contained in:
Tom Hombergs 2018-04-02 22:11:06 +02:00 committed by GitHub
commit 8db0635841
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 97 additions and 0 deletions

View File

@ -0,0 +1,39 @@
package com.baeldung.filesystem
import java.io.BufferedReader
import java.io.File
import java.io.InputStream
class FileReader {
fun readFileLineByLineUsingForEachLine(fileName: String): List<String> {
val lineList = mutableListOf<String>()
File(fileName).forEachLine { line -> lineList.add(line) }
return lineList
}
fun readFileAsLinesUsingUseLines(fileName: String): List<String> {
val lineList = mutableListOf<String>()
File(fileName).useLines { lines -> lineList.addAll(lines) }
return lineList
}
fun readFileAsLinesUsingBufferedReader(fileName: String): List<String> {
val bufferedReader: BufferedReader = File(fileName).bufferedReader()
return bufferedReader.readLines()
}
fun readFileAsLinesUsingReadLines(fileName: String): List<String> {
return File(fileName).readLines()
}
fun readFileAsTextUsingInputStream(fileName: String): String {
val inputStream: InputStream = File(fileName).inputStream()
return inputStream.readBytes().toString(Charsets.UTF_8)
}
fun readFileDirectlyAsText(fileName: String): String {
return File(fileName).readText(Charsets.UTF_8)
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.filesystem
import org.junit.jupiter.api.Test
import kotlin.test.assertTrue
internal class FileReaderTest {
private val fileName = "src/test/resources/Kotlin.in"
private val fileReader = FileReader()
@Test
fun whenReadFileLineByLineUsingForEachLine_thenCorrect() {
val lines = fileReader.readFileLineByLineUsingForEachLine(fileName)
assertTrue { lines.contains("Hello to Kotlin. Its:") }
}
@Test
fun whenReadFileAsLinesUsingUseLines_thenCorrect() {
val lines = fileReader.readFileAsLinesUsingUseLines(fileName)
assertTrue { lines.contains("1. Concise") }
}
@Test
fun whenReadFileAsLinesUsingBufferedReader_thenCorrect() {
val lines = fileReader.readFileAsLinesUsingBufferedReader(fileName)
assertTrue { lines.contains("2. Safe") }
}
@Test
fun whenReadFileAsLinesUsingReadLines_thenCorrect() {
val lines = fileReader.readFileAsLinesUsingReadLines(fileName)
assertTrue { lines.contains("3. Interoperable") }
}
@Test
fun whenReadFileAsTextUsingInputStream_thenCorrect() {
val text = fileReader.readFileAsTextUsingInputStream(fileName)
assertTrue { text.contains("4. Tool-friendly") }
}
@Test
fun whenReadDirectlyAsText_thenCorrect() {
val text = fileReader.readFileDirectlyAsText(fileName)
assertTrue { text.contains("Hello to Kotlin") }
}
}

View File

@ -0,0 +1,5 @@
Hello to Kotlin. Its:
1. Concise
2. Safe
3. Interoperable
4. Tool-friendly