在 Java 中将 UTF-8 转换为 ISO-8859-1 - 如何将其保持为单字节 [英] Converting UTF-8 to ISO-8859-1 in Java - how to keep it as single byte

查看:41
本文介绍了在 Java 中将 UTF-8 转换为 ISO-8859-1 - 如何将其保持为单字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将用 UTF-8 编码的 java 字符串转换为 ISO-8859-1.例如,在字符串 'âabcd' 中,'â' 在 ISO-8859-1 中表示为 E2.在 UTF-8 中,它表示为两个字节.C3 A2 我相信.当我执行 getbytes(encoding) 然后用 ISO-8859-1 编码的字节创建一个新字符串时,我得到两个不同的字符.¢.有没有其他方法可以做到这一点,以保持字符相同,即 âabcd?

I am trying to convert a string encoded in java in UTF-8 to ISO-8859-1. Say for example, in the string 'âabcd' 'â' is represented in ISO-8859-1 as E2. In UTF-8 it is represented as two bytes. C3 A2 I believe. When I do a getbytes(encoding) and then create a new string with the bytes in ISO-8859-1 encoding, I get a two different chars. â. Is there any other way to do this so as to keep the character the same i.e. âabcd?

推荐答案

如果您正在处理 UTF-16 以外的字符编码,则不应使用 java.lang.Stringchar 原语——你应该只使用 byte[] 数组或 ByteBuffer 对象.然后,您可以使用 java.nio.charset.Charset 在编码之间进行转换:

If you're dealing with character encodings other than UTF-16, you shouldn't be using java.lang.String or the char primitive -- you should only be using byte[] arrays or ByteBuffer objects. Then, you can use java.nio.charset.Charset to convert between encodings:

Charset utf8charset = Charset.forName("UTF-8");
Charset iso88591charset = Charset.forName("ISO-8859-1");

ByteBuffer inputBuffer = ByteBuffer.wrap(new byte[]{(byte)0xC3, (byte)0xA2});

// decode UTF-8
CharBuffer data = utf8charset.decode(inputBuffer);

// encode ISO-8559-1
ByteBuffer outputBuffer = iso88591charset.encode(data);
byte[] outputData = outputBuffer.array();

这篇关于在 Java 中将 UTF-8 转换为 ISO-8859-1 - 如何将其保持为单字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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