Domanda

In Java, ho una stringa e voglio codificarla come un array di byte (in UTF8 o qualche altra codifica).In alternativa, ho un array di byte (in alcune codifiche conosciute) e voglio convertirlo in una stringa Java.Come faccio a fare queste conversioni?

È stato utile?

Soluzione

Converti da String a byte[]:

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

Converti da byte[] a String:

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

Dovresti, ovviamente, usare il nome di codifica corretto.I miei esempi utilizzavano US-ASCII e UTF-8, le due codifiche più comuni.

Altri suggerimenti

Ecco una soluzione che evita di eseguire la ricerca del set di caratteri per ogni conversione:

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

Puoi convertire direttamente tramite il file Stringa(byte[], Stringa) costruttore e metodo getBytes(String).Java espone i set di caratteri disponibili tramite il file Carattere classe.La documentazione JDK elenca le codifiche supportate.

Il 90% delle volte, tali conversioni vengono eseguite sugli stream, quindi utilizzeresti il ​​file Lettore/scrittore classi.Non decodificheresti in modo incrementale utilizzando i metodi String su flussi di byte arbitrari: ti lasceresti aperto a bug che coinvolgono caratteri multibyte.

La mia implementazione di Tomcat7 accetta stringhe come ISO-8859-1;nonostante il tipo di contenuto della richiesta HTTP.La seguente soluzione ha funzionato per me quando cercavo di interpretare correttamente caratteri come 'é' .

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

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

Quando si tenta di interpretare la stringa come US-ASCII, le informazioni sui byte non sono state interpretate correttamente.

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

Come alternativa, StringUtils da Apache Commons può essere utilizzato.

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

O

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

Se hai un set di caratteri non standard, puoi usare getBytesUnchecked() O nuovaStringa() di conseguenza.

Per decodificare una serie di byte in un normale messaggio di stringa ho finalmente funzionato con la codifica UTF-8 con questo codice:

/* 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"));
}

Se utilizzi ASCII a 7 bit o ISO-8859-1 (un formato sorprendentemente comune), non devi crearne uno nuovo java.lang.String affatto.È molto più performante semplicemente trasformare il byte in char:

Esempio completo di lavoro:

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

Se sei non utilizzando caratteri estesi come Ä, Æ, Å, Ç, Ï, Ê E puoi essere sicuro che gli unici valori trasmessi siano i primi 128 caratteri Unicode, quindi questo codice funzionerà anche per UTF-8 e ASCII esteso (come 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);

Non posso commentare ma non voglio aprire una nuova discussione.Ma questo non funziona.Un semplice viaggio di andata e ritorno:

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

Avrei bisogno di b[] lo stesso array prima e dopo la codifica, cosa che non è (questo si riferisce alla prima risposta).

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

terribilmente tardi ma ho appena riscontrato questo problema e questa è la mia soluzione:

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 );
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top