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


当前回答

将字符串转换为字节[]:

String s = "some text here";
byte[] b = s.getBytes(StandardCharsets.UTF_8);

将字节[]转换为字符串:

byte[] b = {(byte) 99, (byte)97, (byte)116};
String s = new String(b, StandardCharsets.US_ASCII);

当然,您应该使用正确的编码名称。我的示例使用了US-ASCII和UTF-8这两种常用的编码。

其他回答

将字符串转换为字节[]:

String s = "some text here";
byte[] b = s.getBytes(StandardCharsets.UTF_8);

将字节[]转换为字符串:

byte[] b = {(byte) 99, (byte)97, (byte)116};
String s = new String(b, StandardCharsets.US_ASCII);

当然,您应该使用正确的编码名称。我的示例使用了US-ASCII和UTF-8这两种常用的编码。

这里有一个解决方案,避免执行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);
}

为了解码一系列字节到一个正常的字符串消息,我最终得到了它与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"));
}
//query is your json   

 DefaultHttpClient httpClient = new DefaultHttpClient();
 HttpPost postRequest = new HttpPost("http://my.site/test/v1/product/search?qy=");

 StringEntity input = new StringEntity(query, "UTF-8");
 input.setContentType("application/json");
 postRequest.setEntity(input);   
 HttpResponse response=response = httpClient.execute(postRequest);
Reader reader = new BufferedReader(
    new InputStreamReader(
        new ByteArrayInputStream(
            string.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));