Java ByteArrayOutputStream (com exemplos)

Neste tutorial, aprenderemos sobre Java ByteArrayOutputStream e seus métodos com a ajuda de exemplos.

A ByteArrayOutputStreamclasse do java.iopacote pode ser usada para escrever uma matriz de dados de saída (em bytes).

Ele estende a OutputStreamclasse abstrata.

Nota : In ByteArrayOutputStreammantém uma matriz interna de bytes para armazenar os dados.

Crie um ByteArrayOutputStream

Para criar um fluxo de saída da matriz de bytes, devemos importar o java.io.ByteArrayOutputStreampacote primeiro. Depois de importar o pacote, aqui está como podemos criar um fluxo de saída.

 // Creates a ByteArrayOutputStream with default size ByteArrayOutputStream out = new ByteArrayOutputStream(); 

Aqui, criamos um fluxo de saída que gravará dados em uma matriz de bytes com tamanho padrão de 32 bytes. No entanto, podemos alterar o tamanho padrão do array.

 // Creating a ByteArrayOutputStream with specified size ByteArrayOutputStream out = new ByteArrayOutputStream(int size); 

Aqui, o tamanho especifica o comprimento da matriz.

Métodos de ByteArrayOutputStream

A ByteArrayOutputStreamclasse fornece a implementação dos diferentes métodos presentes na OutputStreamclasse.

Método write ()

  • write(int byte) - grava o byte especificado no fluxo de saída
  • write(byte() array) - grava os bytes da matriz especificada para o fluxo de saída
  • write(byte() arr, int start, int length) - escreve o número de bytes igual ao comprimento para o fluxo de saída de uma matriz começando na posição inicial
  • writeTo(ByteArrayOutputStream out1) - grava todos os dados do fluxo de saída atual no fluxo de saída especificado

Exemplo: ByteArrayOutputStream para gravar dados

 import java.io.ByteArrayOutputStream; class Main ( public static void main(String() args) ( String data = "This is a line of text inside the string."; try ( // Creates an output stream ByteArrayOutputStream out = new ByteArrayOutputStream(); byte() array = data.getBytes(); // Writes data to the output stream out.write(array); // Retrieves data from the output stream in string format String streamData = out.toString(); System.out.println("Output stream: " + streamData); out.close(); ) catch(Exception e) ( e.getStackTrace(); ) ) ) 

Resultado

 Fluxo de saída: esta é uma linha de texto dentro da string. 

No exemplo acima, criamos um fluxo de saída da matriz de bytes denominado output.

 ByteArrayOutputStream output = new ByteArrayOutputStream(); 

Para gravar os dados no fluxo de saída, usamos o write()método.

Nota : O getBytes()método usado no programa converte uma string em uma matriz de bytes.

Acessar dados de ByteArrayOutputStream

  • toByteArray() - retorna a matriz presente dentro do fluxo de saída
  • toString() - retorna todos os dados do fluxo de saída em forma de string

Por exemplo,

 import java.io.ByteArrayOutputStream; class Main ( public static void main(String() args) ( String data = "This is data."; try ( // Creates an output stream ByteArrayOutputStream out = new ByteArrayOutputStream(); // Writes data to the output stream out.write(data.getBytes()); // Returns an array of bytes byte() byteData = out.toByteArray(); System.out.print("Data using toByteArray(): "); for(int i=0; i 

Output

 Data using toByteArray(): This is data. Data using toString(): This is data. 

In the above example, we have created an array of bytes to store the data returned by the toByteArray() method.

We then have used the for loop to access each byte from the array. Here, each byte is converted into the corresponding character using typecasting.

close() Method

To close the output stream, we can use the close() method.

However, the close() method has no effect in ByteArrayOutputStream class. We can use the methods of this class even after the close() method is called.

Other Methods of ByteArrayOutputStream

Métodos Descrições
size() retorna o tamanho da matriz no fluxo de saída
flush() limpa o fluxo de saída

To learn more, visit Java ByteArrayOutputStream (official Java documentation).

Artigos interessantes...