如何在Java / Scala中跳过流中的无效字符?

尤拉:

例如我有以下代码

Source.fromFile(new File( path), "UTF-8").getLines()

并引发异常

Exception in thread "main" java.nio.charset.MalformedInputException: Input length = 1
    at java.nio.charset.CoderResult.throwException(CoderResult.java:260)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:319)

我不在乎是否未读取某些行,但是如何跳过无效字符并继续读取行?

约阿希姆·绍尔(Joachim Sauer):

您可以通过调用来影响字符集解码处理无效输入的方式CharsetDecoder.onMalformedInput

通常,您永远不会CharsetDecoder直接看到对象,因为它将在后台为您创建。因此,如果需要访问它,则需要使用API​​,该API允许您CharsetDecoder直接指定(而不是仅编码名称或Charset)。

此类API的最基本示例是InputStreamReader

InputStream in = ...;
CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
decoder.onMalformedInput(CodingErrorAction.IGNORE);
Reader reader = new InputStreamReader(in, decoder);

请注意,此代码使用了Java 7类StandardCharsets,对于早期版本,你可以简单地替换它Charset.forName("UTF-8")(或使用Charsets番石榴)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章