Јава БитеАрраиОутпутСтреам (са примерима)

У овом упутству ћемо научити о Јави БитеАрраиОутпутСтреам и њеним методама уз помоћ примера.

ByteArrayOutputStreamКласа у java.ioпакету може да се користи за писање низ излазних података (у бајтовима).

Проширује OutputStreamапстрактну класу.

Напомена : Ин ByteArrayOutputStreamодржава интерни низ бајтова за чување података.

Направите БитеАрраиОутпутСтреам

Да бисмо креирали излазни ток бајт поља, прво морамо да увозимо java.io.ByteArrayOutputStreamпакет. Једном када увозимо пакет, ево како можемо створити излазни ток.

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

Овде смо креирали излазни ток који ће уписивати податке у низ бајтова са подразумеваном величином 32 бајта. Међутим, можемо променити подразумевану величину низа.

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

Овде величина одређује дужину низа.

Методе БитеАрраиОутпутСтреам

ByteArrayOutputStreamКласа даје примену различитих метода присутних у OutputStreamкласи.

метода врите ()

  • write(int byte) - уписује наведени бајт у излазни ток
  • write(byte() array) - уписује бајтове из наведеног низа у излазни ток
  • write(byte() arr, int start, int length) - записује број бајтова једнак дужини у излазни ток из низа почев од почетка положаја
  • writeTo(ByteArrayOutputStream out1) - уписује целокупне податке тренутног излазног тока у наведени излазни ток

Пример: БитеАрраиОутпутСтреам за писање података

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

Оутпут

 Излазни ток: Ово је ред текста унутар низа. 

У горњем примеру смо креирали излазни ток бајтног низа под називом оутпут.

 ByteArrayOutputStream output = new ByteArrayOutputStream(); 

Да бисмо записали податке у излазни ток, користили смо write()методу.

Напомена : getBytes()Метода коришћена у програму претвара низ у низ бајтова.

Приступ подацима из БитеАрраиОутпутСтреам

  • toByteArray() - враћа низ присутан унутар излазног тока
  • toString() - враћа целокупне податке излазног тока у облику низа

На пример,

 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

Методе Описи
size() враћа величину низа у излазном току
flush() брише излазни ток

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

Занимљиви Чланци...