Cómo convertir cadenas a y desde matrices de bytes UTF8 en Java


En Java, tengo una cadena y quiero codificarla como una matriz de bytes (en UTF8, o alguna otra codificación). Alternativamente, tengo una matriz de bytes (en alguna codificación conocida) y quiero convertirlo en una cadena Java. ¿Cómo hago estas conversiones?

Author: mcherm, 2008-09-18

13 answers

Convertir de cadena a byte []:

String s = "some text here";
byte[] b = s.getBytes("UTF-8");

Convertir de byte [] a Cadena:

byte[] b = {(byte) 99, (byte)97, (byte)116};
String s = new String(b, "US-ASCII");

Por supuesto, debe usar el nombre de codificación correcto. Mis ejemplos usaban "US-ASCII" y "UTF-8", las dos codificaciones más comunes.

 272
Author: mcherm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-18 00:16:39

Aquí hay una solución que evita realizar la búsqueda de conjuntos de caracteres para cada conversión:

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);
}
 87
Author: Mike Leonhard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-03 05:02:09
String original = "hello world";
byte[] utf8Bytes = original.getBytes("UTF-8");
 17
Author: Jorge Ferreira,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-18 12:53:48

Puede convertir directamente a través del constructor String(byte [], String) y el método getBytes(String). Java expone conjuntos de caracteres disponibles a través de la clase Charset. La documentación JDK lista las codificaciones soportadas.

El 90% de las veces, dichas conversiones se realizan en flujos, por lo que usarías el Lector /Writer clases. No decodificaría de forma incremental usando los métodos de cadena en flujos de bytes arbitrarios - se dejaría abierto a errores que involucran personajes multibyte.

 14
Author: McDowell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-18 11:32:38

Mi implementación tomcat7 está aceptando cadenas como ISO-8859-1; a pesar del tipo de contenido de la solicitud HTTP. La siguiente solución funcionó para mí al tratar de interpretar correctamente caracteres como 'é'.

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

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

Al intentar interpretar la cadena como US-ASCII, la información de bytes no se interpretó correctamente.

b1 = szP1.getBytes("US-ASCII");
System.out.println(b1.toString());
 12
Author: paiego,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-19 20:38:27

Como alternativa, se puede usar StringUtils de Apache Commons.

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

O

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

Si tiene un conjunto de caracteres no estándar, puede usar getBytesUnchecked() o newString() en consecuencia.

 6
Author: vtor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-11 14:32:09

Si está utilizando ASCII de 7 bits o ISO-8859-1 (un formato increíblemente común), entonces no tiene que crear un nuevo java.lang.String en absoluto. Es mucho más performante simplemente lanzar el byte en char:

Ejemplo completo de trabajo:

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

Si eres no usando caracteres extendidos como Ä, Æ, Å, Ç, Ï, Ê y puedes estar seguro de que los únicos valores transmitidos son los primeros 128 caracteres Unicode, entonces este código también funcionará para UTF-8 y ASCII extendido (como cp-1252).

 1
Author: Pacerier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-17 12:31:15

Para decodificar una serie de bytes a un mensaje de cadena normal, finalmente lo conseguí trabajando con la codificación UTF-8 con este código:

/* 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
Author: Bouke Woudstra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-01 07:12:28
//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);
 0
Author: Ran Adler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-01 09:30:56

No puedo comentar, pero no quiero iniciar un nuevo hilo. Pero esto no está funcionando. Un simple viaje de ida y vuelta:

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

Necesitaría b [] la misma matriz antes y después de la codificación que no lo es (esto hace referencia a la primera respuesta).

 0
Author: jschober,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-12 18:10:59
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
Author: Nitish Raj Srivastava,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-31 22:13:05
Reader reader = new BufferedReader(
    new InputStreamReader(
        new ByteArrayInputStream(
            string.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));
 0
Author: Макс Даниленко,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-31 22:15:47

Terriblemente tarde, pero acabo de encontrar este problema y esta es mi solución:

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 );
}
 -9
Author: savio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-19 00:04:18