Why am I getting java.nio.BufferUnderflowException in this Scala

I tried to script in Scala to process some log files:

scala> import io.Source
import io.Source

scala> import java.io.File
import java.io.File

scala> val f = new File(".")
f: java.io.File = .

scala> for (l <- f.listFiles) {
 |   val src = Source.fromFile(l).getLines
 |   println( (0 /: src) { (i, line) => i + 1 } )
 | }
3658
java.nio.BufferUnderflowException
        at java.nio.Buffer.nextGetIndex(Unknown Source)
        at java.nio.HeapCharBuffer.get(Unknown Source)
        at scala.io.BufferedSource$$anon$2.next(BufferedSource.scala:86)
        at scala.io.BufferedSource$$anon$2.next(BufferedSource.scala:74)
        at scala.io.Source$$anon$6.next(Source.scala:307)
        at scala.io.Source$$anon$6.next(Source.scala:301)
        at scala.Iterator$cla...

Why am I getting this java.nio.BufferUnderflowException?

NOTE. - I process 10 log files, each about 1 MB in size.

+5
source share
3 answers

I would also be interested to know why this happens, but I assume that this is due to the fact that it Sourceis an object (i.e. a singleton) and how it becomes transparent reset. You can fix the problem as follows:

for (l <- g.listFiles if !l.isDirectory) {
 | val src = Source.fromFile(l)
 | println( (0 /: src.getLines) { (i, line) => i + 1 } )
 | src.reset
 | }

reset, , , try-finally ( isDirectory, , )

+2

BufferUnderflowException, . ( ), .

+6

, , Elazar, , scala.io.Source.fromFile.

( .jpg fromFile) - , ...

+1

All Articles