Reputation: 8043
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?
Upvotes: 2
Views: 1268
Reputation: 10764
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.
Upvotes: 4