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


当前回答

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

其他回答

String original = "hello world";
byte[] utf8Bytes = original.getBytes("UTF-8");
Charset UTF8_CHARSET = Charset.forName("UTF-8");
String strISO = "{\"name\":\"א\"}";
System.out.println(strISO);
byte[] b = strISO.getBytes();
for (byte c: b) {
    System.out.print("[" + c + "]");
}
String str = new String(b, UTF8_CHARSET);
System.out.println(str);
Reader reader = new BufferedReader(
    new InputStreamReader(
        new ByteArrayInputStream(
            string.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));

我的tomcat7实现是接受字符串作为ISO-8859-1;不管HTTP请求的内容类型是什么。当我试图正确解释'é'这样的字符时,下面的解决方案对我有效。

byte[] b1 = szP1.getBytes("ISO-8859-1");
System.out.println(b1.toString());

String szUT8 = new String(b1, "UTF-8");
System.out.println(szUT8);

当试图将字符串解释为US-ASCII时,字节信息没有正确解释。

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

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

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