Source.fromInputStream读取行中的异常处理 [英] Source.fromInputStream exception handling during reading lines
问题描述
def lineEntry(fileInputStream:InputStream):Iterator [String] = {
源。 fromInputStream(fileInputStream).getLines()
}
我使用的方法如下: / p>
val fStream = getSomeInputStreamFromSource()
lineEntry(fStream).foreach {
processTheLine(_)
}
现在很有可能的是,如果方法lineEntry遇到不良字符而使用foreach迭代输入流。
有什么方法来应对这种情况?
快速解决方案(适用于Scala 2.10):
def lineEntry(fileInputStream:InputStream) :Iterator [String] = {
隐式val编解码器= Codec.UTF8 //或任何其他你喜欢
codec.onMalformedInput(CodingErrorAction.IGNORE)
Source.fromInputStream(fileInputStream ).getLines()
}
在Scala 2.9中有一个小的区别:
隐式编解码器=编解码器(Codec.UTF8)
编解码器
还有一些配置选项,您可以在这种情况下调整其行为。
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.
这篇关于Source.fromInputStream读取行中的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!