在Java中,我有一个字符串,我想将它编码为字节数组(在UTF8中,或其他编码中)。或者,我有一个字节数组(在一些已知的编码中),我想将它转换为Java String。我怎么做这些转换?


当前回答

为了解码一系列字节到一个正常的字符串消息,我最终得到了它与UTF-8编码工作与以下代码:

/* Convert a list of UTF-8 numbers to a normal String
 * Usefull for decoding a jms message that is delivered as a sequence of bytes instead of plain text
 */
public String convertUtf8NumbersToString(String[] numbers){
    int length = numbers.length;
    byte[] data = new byte[length];

    for(int i = 0; i< length; i++){
        data[i] = Byte.parseByte(numbers[i]);
    }
    return new String(data, Charset.forName("UTF-8"));
}

其他回答

作为替代,可以使用Apache Commons中的StringUtils。

 byte[] bytes = {(byte) 1};
 String convertedString = StringUtils.newStringUtf8(bytes);

or

 String myString = "example";
 byte[] convertedBytes = StringUtils.getBytesUtf8(myString);

如果你有非标准的字符集,你可以相应地使用getBytesUnchecked()或newString()。

这里有一个解决方案,避免执行Charset查找每次转换:

import java.nio.charset.Charset;

private final Charset UTF8_CHARSET = Charset.forName("UTF-8");

String decodeUTF8(byte[] bytes) {
    return new String(bytes, UTF8_CHARSET);
}

byte[] encodeUTF8(String string) {
    return string.getBytes(UTF8_CHARSET);
}
Reader reader = new BufferedReader(
    new InputStreamReader(
        new ByteArrayInputStream(
            string.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));

我不能评论,但不想开始一个新的线程。但这行不通。一个简单的往返:

byte[] b = new byte[]{ 0, 0, 0, -127 };  // 0x00000081
String s = new String(b,StandardCharsets.UTF_8); // UTF8 = 0x0000, 0x0000,  0x0000, 0xfffd
b = s.getBytes(StandardCharsets.UTF_8); // [0, 0, 0, -17, -65, -67] 0x000000efbfbd != 0x00000081

我需要b[]在编码之前和编码之后是相同的数组(这指向第一个答案)。

String original = "hello world";
byte[] utf8Bytes = original.getBytes("UTF-8");