简体   繁体   中英

Source.fromInputStream exception handling during reading lines

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM