为什么在这个Scala中得到一个java.nio.BufferUnderflowException? [英] Why do I get a java.nio.BufferUnderflowException in this Scala
问题描述
我试图在Scala中使用一些脚本, a>,来处理一些日志文件:
scala>导入io.Source
导入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 $ b $ java.nio.Buffer.nextGetIndex(Unknown Source)
在java.nio.HeapCharBuffer.get(Unknown Source)
在scala.io.BufferedSource $$ anon $ 2.next(BufferedSource.scala:86)
在scala.io.BufferedSource $$ anon $ 2.next(BufferedSource.scala:74)
在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
我也有兴趣知道为什么发生这种情况,但我猜这是为了处理 Source
是一个对象(即单例),它是如何透明地重置的。您可以如下解决问题:
pre $ for(l < - g.listFiles if!l.isDirectory){
| val src = Source.fromFile(l)
| println((0 /:src.getLines){(i,line)=> i + 1})
| src.reset
| }
重要的是 reset $ c $ (尽管
isDirectory
test可能应该在 try-finally
也是有用的)
I was trying to do some scripting in Scala, to process some log files:
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
?
NOTE - I'm processing 10 log files, each about 1MB in size
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 (i.e. a singleton) and how it is gets transparently reset. 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)
这篇关于为什么在这个Scala中得到一个java.nio.BufferUnderflowException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!