![](/img/trans.png)
[英]java.nio.BufferUnderflowException when processing files in Scala
[英]Why do I get a java.nio.BufferUnderflowException in this 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
当我用错误的BufferUnderflowException
打开文件时,我得到了BufferUnderflowException
异常。 它包含非法字符(根据错误的编码),并引发了这种误导性的异常。
我也很感兴趣为什么会发生这种情况,但我猜这与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
测试也可能有用)
这基本上是对Elazar的回答的重述,但是如果你尝试使用scala.io.Source.fromFile
读取二进制文件,你也会得到这个异常。
我刚碰到这个(不小心试图用fromFile
读取.jpg),因为我写的东西中有一个非常愚蠢的错误...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.