为什么我在这个Scala中得到java.nio.BufferUnderflowException

tha*_*att 5 file-io scala bufferunderflowexception

我试图在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...
Run Code Online (Sandbox Code Playgroud)

为什么我这样做java.nio.BufferUnderflowException

注意 - 我正在处理10个日志文件,每个文件大小约为1MB

Ela*_*ich 6

BufferUnderflowException当我用错误的enconding打开文件时,我遇到了异常.它包含非法字符(根据错误的编码),并引发了这种误导性的异常.


oxb*_*kes 2

我也很想知道为什么会发生这种情况,但我猜这与Source对象(即单例)以及它如何透明地重置这一事实有关。您可以按如下方式解决该问题:

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

重要的一点是reset- 它可能应该在一个try-finally块中(尽管isDirectory测试可能也很有用)