如何在Java中将字符串转换为UTF8字节数组以及如何将UTF8字节数组转换为字符串

293

在Java中,我有一个字符串,想将其编码为字节数组(UTF8或其他编码)。另外,我有一个字节数组(使用某种已知编码),想将其转换为Java字符串。如何进行这些转换?

以下是示例代码:

将字符串编码为字节数组:

String str = "Hello, world!";
byte[] bytes = str.getBytes("UTF-8");

将字节数组转换为字符串:

byte[] bytes = new byte[]{72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33};
String str = new String(bytes, "UTF-8");
13个回答

0
Reader reader = new BufferedReader(
    new InputStreamReader(
        new ByteArrayInputStream(
            string.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));

-1
//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);

String Entity会将“query”转换为utf-8,还是只在附加实体时记住? - SyntaxRules

-10

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

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 );
}

2
首先,这不是转换:它是非可打印字节的删除。其次,它假定底层操作系统的默认编码确实基于ASCII可打印字符(例如,在使用EBCDIC的IBM大型机上将无法正常工作)。 - Isaac

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接