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

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

问题描述

我正在尝试将UTF-8中编码的字符串转换为ISO-8859-1。比如说,在字符串'âabcd''中,在ISO-8859-1中表示为E2。在UTF-8中,它表示为两个字节。 C3 A2我相信。当我执行getbytes(编码)然后使用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.String char 原语 - - 你应该只使用 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天全站免登陆