How to convert Strings to and from UTF8 byte arrays in Java

前端 未结 13 2330
终归单人心
终归单人心 2020-11-22 13:05

In Java, I have a String and I want to encode it as a byte array (in UTF8, or some other encoding). Alternately, I have a byte array (in some known encoding) and I want to c

13条回答
  •  故里飘歌
    2020-11-22 13:39

    My tomcat7 implementation is accepting strings as ISO-8859-1; despite the content-type of the HTTP request. The following solution worked for me when trying to correctly interpret characters like 'é' .

    byte[] b1 = szP1.getBytes("ISO-8859-1");
    System.out.println(b1.toString());
    
    String szUT8 = new String(b1, "UTF-8");
    System.out.println(szUT8);
    

    When trying to interpret the string as US-ASCII, the byte info wasn't correctly interpreted.

    b1 = szP1.getBytes("US-ASCII");
    System.out.println(b1.toString());
    

提交回复
热议问题