FileReader idiomatic refactor (#3936)

This commit is contained in:
Grzegorz Piwowarek 2018-04-11 12:20:33 +02:00 committed by GitHub
parent 0e95588c54
commit 64e9b41aef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 8 additions and 27 deletions

View File

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