lexu lexu - 3 years ago 141
Scala Question

Reading a text file in scala, one line after the other, not iterated

I'm trying to open a text file with Scala, read the first line, then the second, then the third.

All samples I've found online want to read/buffer the entire file into a list or array and then access the individual lines from that construct.

This code doesn't work as described above(of course).
It reads the entire file into "first" since "file" is a BufferedStream and getLines fetches all lines, as it should.

import scala.io.Source;
object ScalaDemo {
def main(args: Array[String]) = {
val file = io.Source.fromFile("TextFile.txt");

// -----------------------------------------------
// read text from file, line by line, no iterator
// -----------------------------------------------
val first = file.getLines().mkString;
val second = file.getLines().mkString;
val third = file.getLines().mkString;

// Close the file


What idiom/function can I use to read one line at a time... without using a list/array as an intermediate step.

Answer Source

As stated in comments, .mkString will fetch all the elements that the iterator would return and concatenate them in a single string.

The option of @RĂ©gis Jean-Gilles is probably the best if you already know that you always have at least three lines in the file.

Another option is to call getLines() followed by grouped(3) to get an iterator that groups elements into blocks of 3. A call to next() will give you a list with at most three elements (it can have less if the iterator has only two elements left to return for example).

val ite = io.Source.fromFile("textfile.txt").getLines().grouped(3)

//list with the first three elements, if any -  
//otherwise an empty list if the file is empty
val list = if(ite.hasNext()) ite.next() else Nil 

At least it does ensure that you won't have a NoSuchElementException at runtime if there is less than 3 lines in the file.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download