Skip to content

Instantly share code, notes, and snippets.

@GregKluska
Last active November 26, 2022 18:16
Show Gist options
  • Select an option

  • Save GregKluska/5332eb84e38a4df8d54ef44d3c322ba0 to your computer and use it in GitHub Desktop.

Select an option

Save GregKluska/5332eb84e38a4df8d54ef44d3c322ba0 to your computer and use it in GitHub Desktop.
Loading a text file to a script
fun readFileLineByLineUsingForEachLine(fileName: String)
= File(fileName).forEachLine { println(it) }
private fun processData(fileName: String, block: (line: String) -> Unit) {
val file = File(fileName)
try {
BufferedReader(FileReader(file)).use { br ->
var line: String?
while (br.readLine().also { line = it } != null) {
line?.let { block(it) }
}
}
} catch (e: IOException) {
println("Unable to read the file")
e.printStackTrace()
}
}
private fun processData(fileName: String, block: (line: String) -> Unit) {
try {
object {}.javaClass.getResourceAsStream(fileName)?.bufferedReader()?.use { br ->
var line: String?
while (br.readLine().also { line = it } != null) {
line?.let { block(it) }
}
}
} catch (e: IOException) {
println("Unable to read the file")
e.printStackTrace()
}
}
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.io.IOException
fun main() {
val file = File("/home/data/file.txt")
try {
BufferedReader(FileReader(file)).use { br ->
var line: String?
while (br.readLine().also { line = it } != null) {
println(line)
}
}
} catch (e: IOException) {
e.printStackTrace()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment