Read first line from huge File in Kotlin

Viewed 3866

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()
2 Answers

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.

Related