为什么我在这个 Scala 中得到一个 java.nio.BufferUnderflowException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1048618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why do I get a java.nio.BufferUnderflowException in this Scala
提问by thatismatt
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.next(BufferedSource.scala:86)
at scala.io.BufferedSource$$anon.next(BufferedSource.scala:74)
at scala.io.Source$$anon.next(Source.scala:307)
at scala.io.Source$$anon.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
采纳答案by oxbow_lakes
I'd also be interested as to exactly why this is happening but I'd guess it's to do with the fact that Sourceis an object (i.e. a singleton) and how it is gets transparentlyreset. You can fix the problem as follows:
我也很想知道为什么会发生这种情况,但我猜这与Source作为对象(即单例)的事实以及它如何透明地重置有关。您可以按如下方式解决问题:
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-finallyblock (although the isDirectorytest is probably useful too)
重要的一点是reset- 它可能应该在一个try-finally块中(尽管isDirectory测试可能也很有用)
回答by Elazar Leibovich
I got BufferUnderflowExceptionexception when I opened a file with the wrong enconding. It contained illegal characters (according to the wrong encoding) and this misleading exception was thrown.
BufferUnderflowException当我打开一个带有错误编码的文件时出现异常。它包含非法字符(根据错误的编码),并抛出了这个误导性异常。
回答by overthink
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 )...

