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
file.close;
println(first+"|"+second+"|"+third);
}
}
What idiom/function can I use to read one line at a time... without using a list/array as an intermediate step.
val lines = file.getLines(); val first,second,third = lines.next
– Régis Jean-Gilles Jun 16 '15 at 9:57