Reading a certain number of lines from a file

2018-02-02 21:29:08

def getLinesFromFile(file:File, linesToGet:Int): List[String] ={

val bufferedSource = Source.fromFile(file)

val lb = ListBuffer[String]()

try {

val lines = bufferedSource.getLines()

var counter = 0

while (lines.hasNext && counter < linesToGet) {

counter += 1

lb.append(lines.next())

}

} finally {

bufferedSource.close()

}

lb.toList

}

I am trying to retrieve a certain amount of lines from a read text file, and return each line as a List back to the user. Validation for the file actually being a .txt file is done prior to this call, and I can say with certainty that each line won't be longer than @500 characters.

My primary concern is I'm wondering if there any reason this code would create any memory leaks?

That implementation is very procedural. getLines() returns an Iterator, which supports a take(n) method.

def getLinesFromFile(file:File, linesToGet:Int): List[String] = {

val bufferedSo

  • That implementation is very procedural. getLines() returns an Iterator, which supports a take(n) method.

    def getLinesFromFile(file:File, linesToGet:Int): List[String] = {

    val bufferedSource = Source.fromFile(file)

    try {

    bufferedSource.getLines.take(linesToGet).toList

    } finally {

    bufferedSource.close

    }

    }

    2018-02-02 23:16:59