Source.fromInputStream exception handling during reading lines

主宰稳场 提交于 2019-12-10 10:36:05

问题


I have created a function where I take in as a parameter an inputstream and return an iterator consisting of a string. I accomplish this as follows:

def lineEntry(fileInputStream:InputStream):Iterator[String] = {
   Source.fromInputStream(fileInputStream).getLines()
}

I use the method as follows:

val fStream = getSomeInputStreamFromSource()
lineEntry(fStream).foreach{
  processTheLine(_)
}

Now it is quite possible that the method lineEntry might blow up if it encounters a bad character while it's iterating over the inputstream using the foreach.

What are some of the ways to counter this situation?


回答1:


Quick solution (for Scala 2.10):

def lineEntry(fileInputStream:InputStream):Iterator[String] = {
  implicit val codec = Codec.UTF8 // or any other you like
  codec.onMalformedInput(CodingErrorAction.IGNORE)

  Source.fromInputStream(fileInputStream).getLines()
}

In Scala 2.9 there's a small difference:

implicit val codec = Codec(Codec.UTF8)

Codec has also a few more configuration options with which you can tune its behaviour in such cases.



来源:https://stackoverflow.com/questions/15845422/source-frominputstream-exception-handling-during-reading-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!