如何将字符串转换为从Java中的UTF8字节数组

问题描述 投票:211回答:13

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

java string encoding character-encoding
13个回答
316
投票

从字符串转换成字节[]:

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,最常见的两种编码。


0
投票

我不能评论,但不希望启动一个新的线程。但是,这是行不通的。一个简单的往返:

byte[] b = new byte[]{ 0, 0, 0, -127 };  // 0x00000081
String s = new String(b,StandardCharsets.UTF_8); // UTF8 = 0x0000, 0x0000,  0x0000, 0xfffd
b = s.getBytes(StandardCharsets.UTF_8); // [0, 0, 0, -17, -65, -67] 0x000000efbfbd != 0x00000081

我以前和编码它不是(此引荐到第一应答)后需要B []相同的数组。


0
投票
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);

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

-9
投票

非常晚,但我只遇到过这个问题,这是我的解决办法:

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

92
投票

下面是避免了每次转换执行字符集查找的解决方案:

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

17
投票
String original = "hello world";
byte[] utf8Bytes = original.getBytes("UTF-8");

14
投票

您可以通过String(byte[], String)构造函数和的getBytes(String)方法直接转换。 Java的通过Charset类公开可用的字符集。 JDK文档lists supported encodings

90%的时间,这种转换是在流执行,所以你最好使用Reader / Writer类。你不会逐步使用解码任意字节流的字符串方法 -​​ 你会把自己暴露给涉及多字节字符错误。


12
投票

我tomcat7实现接受字符串作为ISO-8859-1;尽管内容类型的HTTP请求。下面的解决方案试图正确地解释像“E”字符的时候为我工作。

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

7
投票

作为替代方案,可以使用从Apache的百科全书StringUtils

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

要么

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

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


2
投票

对于一系列的字节进行解码,以正常的字符串消息我终于得到它使用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"));
}

1
投票

如果使用的是7位ASCII或ISO-8859-1(一个令人惊讶的通用格式),那么你不必再创建一个新的java.lang.String。这是很多很多更好的性能,简单的字节流延成char:

全部工作示例:

for (byte b : new byte[] { 43, 45, (byte) 215, (byte) 247 }) {
    char c = (char) b;
    System.out.print(c);
}

如果你不使用扩展字符,如A,AE,A,C,I,E,可以肯定的是,仅传送值是第128个Unicode字符,那么这段代码也将努力为UTF-8扩展ASCII (如CP-1252)。


0
投票
//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);
© www.soinside.com 2019 - 2024. All rights reserved.