Source.fromInputStream读取行中的异常处理 [英] Source.fromInputStream exception handling during reading lines

查看:397
本文介绍了Source.fromInputStream读取行中的异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个函数,作为参数输入一个输入流,并返回一个由一个字符串组成的迭代器。我完成了如下:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆