pixel
pixel

Reputation: 26441

Read first line from huge File in Kotlin

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

Upvotes: 11

Views: 6131

Answers (2)

apetranzilla
apetranzilla

Reputation: 5929

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.

Upvotes: 7

Roland
Roland

Reputation: 23242

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).

Upvotes: 17

Related Questions