簡體   English   中英

如何在Java中將字符串轉換為UTF8字節數組

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

在Java中,我有一個字符串,我想將其編碼為字節數組(UTF8或其他編碼)。 或者,我有一個字節數組(在一些已知的編碼中),我想將其轉換為Java字符串。 我該如何進行這些轉換?

從String轉換為byte []:

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

從byte []轉換為String:

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

當然,您應該使用正確的編碼名稱。 我的例子使用了US-ASCII和UTF-8這兩種最常見的編碼。

這是一個避免為每次轉換執行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");

您可以直接通過String(byte [],String)構造函數和getBytes(String)方法進行轉換。 Java通過Charset類公開可用的字符集。 JDK文檔列出了支持的編碼

90%的情況下,此類轉換是在流上執行的,因此您將使用Reader / Writer類。 您不會在任意字節流上使用String方法進行增量解碼 - 您可能會對涉及多字節字符的錯誤開放。

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

作為替代方案,可以使用Apache Commons的StringUtils

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

要么

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

如果您有非標准字符集,則可以相應地使用getBytesUnchecked()newString()

為了將一系列字節解碼為普通字符串消息,我終於使用此代碼使用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"));
}

如果您使用的是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);
}

如果你沒有使用像Ä,Æ,Å,Ç,Ï,Ê這樣的擴展字符並且可以確保唯一傳輸的值是前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));

我無法評論,但不想開始一個新的線程。 但這不起作用。 一次簡單的往返:

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 []在編碼之前和之后的相同數組,它不是(這是第一個答案的引用)。

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

非常晚,但我剛遇到這個問題,這是我的修復:

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