简体   繁体   English

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

[英]How to convert Strings to and from UTF8 byte arrays in Java

In Java, I have a String and I want to encode it as a byte array (in UTF8, or some other encoding). 在Java中,我有一个字符串,我想将其编码为字节数组(UTF8或其他编码)。 Alternately, I have a byte array (in some known encoding) and I want to convert it into a Java String. 或者,我有一个字节数组(在一些已知的编码中),我想将其转换为Java字符串。 How do I do these conversions? 我该如何进行这些转换?

Convert from String to byte[]: 从String转换为byte []:

String s = "some text here";
byte[] b = s.getBytes(StandardCharsets.UTF_8);

Convert from byte[] to String: 从byte []转换为String:

byte[] b = {(byte) 99, (byte)97, (byte)116};
String s = new String(b, StandardCharsets.US_ASCII);

You should, of course, use the correct encoding name. 当然,您应该使用正确的编码名称。 My examples used US-ASCII and UTF-8, the two most common encodings. 我的例子使用了US-ASCII和UTF-8这两种最常见的编码。

Here's a solution that avoids performing the Charset lookup for every conversion: 这是一个避免为每次转换执行Charset查找的解决方案:

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

You can convert directly via the String(byte[], String) constructor and getBytes(String) method. 您可以直接通过String(byte [],String)构造函数和getBytes(String)方法进行转换。 Java exposes available character sets via the Charset class. Java通过Charset类公开可用的字符集。 The JDK documentation lists supported encodings . JDK文档列出了支持的编码

90% of the time, such conversions are performed on streams, so you'd use the Reader / Writer classes. 90%的情况下,此类转换是在流上执行的,因此您将使用Reader / Writer类。 You would not incrementally decode using the String methods on arbitrary byte streams - you would leave yourself open to bugs involving multibyte characters. 您不会在任意字节流上使用String方法进行增量解码 - 您可能会对涉及多字节字符的错误开放。

My tomcat7 implementation is accepting strings as ISO-8859-1; 我的tomcat7实现接受字符串为ISO-8859-1; despite the content-type of the HTTP request. 尽管HTTP请求的内容类型。 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. 尝试将字符串解释为US-ASCII时,未正确解释字节信息。

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

As an alternative, StringUtils from Apache Commons can be used. 作为替代方案,可以使用Apache Commons的StringUtils

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

or 要么

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

If you have non-standard charset, you can use getBytesUnchecked() or newString() accordingly. 如果您有非标准字符集,则可以相应地使用getBytesUnchecked()newString()

For decoding a series of bytes to a normal string message I finally got it working with UTF-8 encoding with this code: 为了将一系列字节解码为普通字符串消息,我终于使用此代码使用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"));
}

If you are using 7-bit ASCII or ISO-8859-1 (an amazingly common format) then you don't have to create a new java.lang.String at all. 如果您使用的是7位ASCII或ISO-8859-1(一种非常常见的格式),那么您根本不必创建新的java.lang.String It's much much more performant to simply cast the byte into char: 简单地将字节转换为char更加高效:

Full working example: 完整的工作示例:

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

If you are not using extended-characters like Ä, Æ, Å, Ç, Ï, Ê and can be sure that the only transmitted values are of the first 128 Unicode characters, then this code will also work for UTF-8 and extended ASCII (like cp-1252). 如果你没有使用像Ä,Æ,Å,Ç,Ï,Ê这样的扩展字符并且可以确保唯一传输的值是前128个Unicode字符,则此代码也适用于UTF-8和扩展ASCII (如cp-1252)。

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

I can't comment but don't want to start a new thread. 我无法评论,但不想开始一个新的线程。 But this isn't working. 但这不起作用。 A simple round trip: 一次简单的往返:

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

I'd need b[] the same array before and after encoding which it isn't (this referrers to the first answer). 我需要b []在编码之前和之后的相同数组,它不是(这是第一个答案的引用)。

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

terribly late but i just encountered this issue and this is my fix: 非常晚,但我刚遇到这个问题,这是我的修复:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM