Why do I get a java.nio.BufferUnderflowException in this Scala

泄露秘密 提交于 2019-12-04 07:38:31

I'd also be interested as to exactly why this is happening but I'd guess it's to do with the fact that Source is an object (i.e. a singleton) and how it is gets transparently 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
 | }

The important bit is the reset - which should probably be in a try-finally block (although the isDirectory test is probably useful too)

I got BufferUnderflowException exception when I opened a file with the wrong enconding. It contained illegal characters (according to the wrong encoding) and this misleading exception was thrown.

This is essentially a restatement of Elazar's answer, but you will also get this exception if you try to read a binary file using scala.io.Source.fromFile.

I just ran into this (accidentally trying to read a .jpg with fromFile) due to a very stupid bug in something I wrote...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!