Yesterday, this piece of code caused me a headache. I fixed it by reading the file line by line. Any ideas ?
The while loop never seems to get executed even though the no of lines in the file is greater than 1.
val lines = Source.fromFile( new File("file.txt") ).getLines;
println( "total lines:"+lines.size );
var starti = 1;
while( starti < lines.size ){
val nexti = Math.min( starti + 10, lines.size );
println( "batch ("+starti+", "+nexti+") total:" + lines.size )
val linesSub = lines.slice(starti, nexti)
//do something with linesSub
starti = nexti
}
This is indeed tricky, and I would even say it’s a bug in
Iterator.getLinesreturns anIteratorwhich proceeds lazily. So what seems to happen is that if you ask forlines.sizethe iterator goes through the whole file to count the lines. Afterwards, it’s “exhausted”:You see, when you execute
sizetwice, the result is zero.There are two solutions, either you force the iterator into something ‘stable’, like
lines.toSeq. Or you forget aboutsizeand do the “normal” iteration: