【问题标题】:Conversion of UTF-8 char to ISO-8859-1将 UTF-8 字符转换为 ISO-8859-1
【发布时间】:2014-08-29 03:06:35
【问题描述】:

我尝试将 UTF8 字符转换为 ISO-8859-1,但所有字符(如 0x84;0x96;)都没有转换为 ISO-8859-1,请参见下面的 java 代码

    static byte[] encode(byte[] arr) throws CharacterCodingException{
           Charset utf8charset = Charset.forName("UTF-8");
           Charset iso88591charset = Charset.forName("ISO-8859-1");    
           ByteBuffer inputBuffer = ByteBuffer.wrap( arr );    
            // decode UTF-8
           CharBuffer data = utf8charset.decode(inputBuffer);    
           // encode ISO-8559-1
            ByteBuffer outputBuffer=  iso88591charset.newEncoder()
                .onMalformedInput(CodingErrorAction.REPLACE)
                .onUnmappableCharacter(CodingErrorAction.REPLACE)
                .encode(data); 
           data = iso88591charset.decode(outputBuffer);
           byte[] outputData = outputBuffer.array();    

           return outputData;
    }

请帮忙解决。 谢谢。

【问题讨论】:

  • 你确定这些字符存在于 ISO-8859-1 中吗?它的维基百科页面说并非所有语言的字符都受支持。您必须找到一种方法将丢失的字符映射到更简单的字符,例如没有口音。

标签: java utf-8 iso-8859-1


【解决方案1】:

首先你可以使用StandardCharsets.UTF_8StandardCharsets.ISO_8859_1

但是,最好将"ISO-8859-1" 替换为"Windows-1252"

原因是浏览器和其他浏览器将 ISO-8859-1 (Latin-1) 的指示解释为 Windows-1252 (Windows Latin-1)。在 Windows Latin-1 中,范围 0x80 - 0xbf 用于类似逗号的引号等。

所以运气好的话(我不认为你的意思是浏览器)这将起作用。

顺便说一句,在浏览器中,这甚至可以在 Mac 上运行,并且从 HTML5 开始是官方的。

【讨论】:

  • 感谢您的回复,但我已经尝试过了,但没有成功。它是一个桌面门户应用程序。
  • 但是看这里ISO-8859-1 - 没有 0x84、0x96。和Windows-1252 - 0x84 和 0x96
  • 是的,那些 Windows-1252 字符必须被过滤掉,否则我应该得到一些例外。我尝试使用由于没有可映射字符而抛出的 encoder.onUnmappableCharacter(CodingErrorAction.REPORT) 来获取异常。
【解决方案2】:

试一试,

    String str = new String(utf8Bytes, "UTF-8");

    byte[] isoBytes = str.getBytes( "ISO-8859-1" );

如果它为您提供完全相同的结果,那么您的字符不会在这些字符集之间映射。

【讨论】:

  • 如果我使用 Report 代替 Replace,它会引发 Unmappable 异常,显示字符不可映射。 // 编码 ISO-8559-1 ByteBuffer outputBuffer= iso88591charset.newEncoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT) .encode(data);
【解决方案3】:

我的猜测是,当您说“0x84,0x96”时,您的意思是字节数组中的字节。 如果是这种情况,您将获取这些字节并尝试将它们解释为 UTF-8,但是 该字节序列不是有效的 UTF-8 序列。

from U+0000  to U+007F   : 1 byte  :  0xxxxxxx
from U+0080  to U+07FF   : 2 bytes :  110xxxxx  10xxxxxx
from U+0800  to U+FFFF   : 3 bytes :  1110xxxx  10xxxxxx  10xxxxxx
from U+10000 to U+1FFFFF : 4 bytes :  11110xxx  10xxxxxx  10xxxxxx  10xxxxxx

由于 84 96 是 0x10000100 0x10010110 与上面的位模式不匹配 (注意前导字节中的 0x11.... 或 0x0....,绝不是 0x10....,即“尾随字节”)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-04
    • 2020-01-25
    • 2012-01-05
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多