Suppose I have a jarfile on my classpath. In that jarfile I have a file afile.txt
.
I need to iterate on that file twice, once to count the lines and o开发者_开发技巧nce to parse it. This is what I did:
val source = Source.fromInputStream(/*some magic to get the resource's InputStream*/)
source.getLines.foreach (/*count the lines*/)
source.getLines.reset.foreach (/*do something interesting*/)
But this doesn't work. In the debugger it looks like the call to reset()
returns an empty iterator. The code above works fine when the Source refers to a file on the filesystem instead of on the classpath.
Am I doing something wrong, or is this a bug in Scala's io library?
I think this is a bug is the Scala library. I had a quick look at Source.scala in 2.8 trunk and reset seems to return a new wrapper around the original input stream which would have no content left after the first pass. I think it should throw an exception. I can't think of a straightforward way you could reset an arbitrary input stream.
I think you can simply call val source2 = Source.fromInputStream
and read again, as it seems reset
does not do more than that.
精彩评论