[英]Why do I get a java.nio.BufferUnderflowException in this Scala
I was trying to do some scripting in Scala , to process some log files: 我试图在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...
Why do I get this java.nio.BufferUnderflowException
? 为什么我会得到这个
java.nio.BufferUnderflowException
?
NOTE - I'm processing 10 log files, each about 1MB in size 注意 - 我正在处理10个日志文件,每个文件大小约为1MB
I got BufferUnderflowException
exception when I opened a file with the wrong enconding. 当我用错误的
BufferUnderflowException
打开文件时,我得到了BufferUnderflowException
异常。 It contained illegal characters (according to the wrong encoding) and this misleading exception was thrown. 它包含非法字符(根据错误的编码),并引发了这种误导性的异常。
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 (ie a singleton) and how it is gets transparently reset. 我也很感兴趣为什么会发生这种情况,但我猜这与
Source
是一个对象(即单例)以及如何透明地重置这一事实有关。 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) 重要的一点是
reset
- 它可能应该在try-finally
块中(虽然isDirectory
测试也可能有用)
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
. 这基本上是对Elazar的回答的重述,但是如果你尝试使用
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... 我刚碰到这个(不小心试图用
fromFile
读取.jpg),因为我写的东西中有一个非常愚蠢的错误...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.