我试图做一些Scala中的脚本,来处理一些日志文件:
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...我为什么要得到这个java.nio.BufferUnderflowException
注意-我正在处理10个日志文件,每个文件的大小约为1MB
发布于 2009-06-26 13:41:50
我还想知道为什么会发生这种情况,但我想这与Source是一个对象(即单例)以及如何透明地重置它有关。您可以按以下方式解决此问题:
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测试可能也很有用)
发布于 2009-09-28 22:15:46
当我打开错误的文件时,我得到了BufferUnderflowException异常。它包含非法字符(根据错误的编码),并且引发了这一误导性异常。
发布于 2009-12-31 04:20:18
这本质上是对Elazar答案的重新声明,但是如果您尝试使用scala.io.Source.fromFile读取二进制文件,您也会得到这个异常。
我只是偶然遇到这个(不小心试图用fromFile阅读一个fromFile),因为我写的东西中有一个非常愚蠢的bug .
https://stackoverflow.com/questions/1048618
复制相似问题