Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 948
pixel Avatar asked Sep 14 '18 14:09

pixel


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

like image 91
Roland Avatar answered Oct 25 '22 17:10

Roland


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.

like image 34
apetranzilla Avatar answered Oct 25 '22 16:10

apetranzilla