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


当前回答

非常晚,但我刚刚遇到了这个问题,这是我的解决方案:

private static String removeNonUtf8CompliantCharacters( final String inString ) {
    if (null == inString ) return null;
    byte[] byteArr = inString.getBytes();
    for ( int i=0; i < byteArr.length; i++ ) {
        byte ch= byteArr[i]; 
        // remove any characters outside the valid UTF-8 range as well as all control characters
        // except tabs and new lines
        if ( !( (ch > 31 && ch < 253 ) || ch == '\t' || ch == '\n' || ch == '\r') ) {
            byteArr[i]=' ';
        }
    }
    return new String( byteArr );
}

其他回答

String original = "hello world";
byte[] utf8Bytes = original.getBytes("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));

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

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这两种常用的编码。

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

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

or

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

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