Java String getBytes ()

O método Java String getBytes () codifica a string em uma sequência de bytes e a armazena em uma matriz de bytes.

A sintaxe do getBytes()método String é:

 string.getBytes() string.getBytes(Charset charset) string.getBytes(String charsetName)

Aqui, string é um objeto da Stringclasse.

O getBytes()método retorna uma matriz de bytes.

1. getBytes () sem quaisquer parâmetros

Se você não passar nenhum parâmetro, getBytes()codifica a string usando o conjunto de caracteres padrão da plataforma.

Exemplo: getBytes () sem nenhum parâmetro

 import java.util.Arrays; class Main ( public static void main(String() args) ( String str = "Java"; byte() byteArray; // convert the string to a byte array // using platform's default charset byteArray = str.getBytes(); System.out.println(Arrays.toString(byteArray)); ) )

Resultado

 (74, 97, 118, 97)

Nota: Usamos a Arraysclasse no exemplo acima para imprimir a matriz de bytes em um formato legível. Não tem nada a ver com getBytes().

2. getBytes () com parâmetro CharSet

Aqui estão os diferentes CharSetdisponíveis em java:

  • UTF-8 - Formato de transformação UCS de oito bits
  • UTF-16 - Formato de Transformação UCS de dezesseis bits
  • UTF-16BE - Formato de Transformação UCS de dezesseis bits, ordem de bytes big-endian
  • UTF-16LE - Formato de Transformação UCS de dezesseis bits, ordem de bytes little-endian
  • US-ASCII - ASCII de sete bits
  • ISO-8859-1 - ISO alfabeto latino nº 1

Exemplo: getBytes () com parâmetro CharSet

 import java.util.Arrays; import java.nio.charset.Charset; class Main ( public static void main(String() args) ( String str = "Java"; byte() byteArray; // using UTF-8 for encoding byteArray = str.getBytes(Charset.forName("UTF-8")); System.out.println(Arrays.toString(byteArray)); // using UTF-16 for encoding byteArray = str.getBytes(Charset.forName("UTF-16")); System.out.println(Arrays.toString(byteArray)); ) )

Resultado

 (74, 97, 118, 97) (-2, -1, 0, 74, 0, 97, 0, 118, 0, 97)

Nota: No programa acima, importamos java.nio.charset.Charsetpara usar CharSet. E importamos a Arraysclasse para imprimir a matriz de bytes em um formato legível.

3. getBytes () com parâmetro de string

Você também pode especificar o tipo de codificação para getBytes()usar strings. Quando você usa getBytes()dessa forma, deve envolver o código dentro do bloco try… catch.

Exemplo: getBytes () com parâmetro de string

 import java.util.Arrays; class Main ( public static void main(String() args) ( String str = "Java"; byte() byteArray; try ( byteArray = str.getBytes("UTF-8"); System.out.println(Arrays.toString(byteArray)); byteArray = str.getBytes("UTF-16"); System.out.println(Arrays.toString(byteArray)); // wrong encoding // throws an exception byteArray = str.getBytes("UTF-34"); System.out.println(Arrays.toString(byteArray)); ) catch (Exception e) ( System.out.println(e + " encoding is wrong"); ) ) )

Resultado

 (74, 97, 118, 97) (-2, -1, 0, 74, 0, 97, 0, 118, 0, 97) java.io.UnsupportedEncodingException: a codificação UTF-34 está errada

Observação: importamos java.util.Arrays para imprimir a matriz de bytes em um formato legível. Não tem nada a ver com isso getBytes().

Artigos interessantes...