I would like to read first (and only) line from File
in kotlin.
File itself is huge so I would like to use memory efficient solution.
I wonder if there is any better solution than:
File("huge.txt").bufferedReader().readLine()
You could use:
file.useLines { it.firstOrNull() }
or:
file.bufferedReader().use { it.readLine() }
Both ensure that you are actually closing your reader after that line and are similarly effective.
If you know for sure that there is always a first line and that the files will never be empty you can also use first()
instead or call it.readLine()!!
(this actually depends on whether you assigned the result to a nullable type or not).
What you have right now is already pretty efficient - the file will be loaded in small chunks by the bufferedReader
until a single line has been read. You should make sure the reader is closed, however - something like this:
File("huge.txt").bufferedReader().use { it.readLine() }
If you don't need speed, using a regular, unbuffered reader may save you a little bit of memory, but not much.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With