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

2024-02-19

例如我有以下代码

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)

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


您可以通过调用来影响字符集解码处理无效输入的方式CharsetDecoder.onMalformedInput http://download.oracle.com/javase/7/docs/api/java/nio/charset/CharsetDecoder.html#onMalformedInput%28java.nio.charset.CodingErrorAction%29.

Usually你永远不会看到CharsetDecoder直接对象,因为它将在幕后为您创建。因此,如果您需要访问它,您需要使用允许您指定的 APICharsetDecoder直接(而不仅仅是编码名称或Charset).

此类 API 最基本的示例是InputStreamReader http://download.oracle.com/javase/7/docs/api/java/io/InputStreamReader.html#InputStreamReader%28java.io.InputStream,%20java.nio.charset.CharsetDecoder%29:

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

请注意,此代码使用 Java 7 类StandardCharsets http://download.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html,对于早期版本,您只需将其替换为Charset.forName("UTF-8") http://download.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html#forName%28java.lang.String%29(或使用the Charsets class http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Charsets.html from Guava http://code.google.com/p/guava-libraries/).

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐