Last active
November 26, 2022 18:16
-
-
Save GregKluska/5332eb84e38a4df8d54ef44d3c322ba0 to your computer and use it in GitHub Desktop.
Loading a text file to a script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| fun readFileLineByLineUsingForEachLine(fileName: String) | |
| = File(fileName).forEachLine { println(it) } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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