Lớp Java ByteArrayOutputStream

Trong hướng dẫn này, chúng ta sẽ tìm hiểu về Java ByteArrayOutputStream và các phương thức của nó với sự trợ giúp của các ví dụ.

Các ByteArrayOutputStreamlớp của java.iogói có thể được sử dụng để viết một loạt các dữ liệu đầu ra (theo byte).

Nó mở rộng OutputStreamlớp trừu tượng.

Lưu ý : Trong ByteArrayOutputStreamduy trì một mảng byte bên trong để lưu trữ dữ liệu.

Tạo một ByteArrayOutputStream

Để tạo luồng đầu ra mảng byte, java.io.ByteArrayOutputStreamtrước tiên chúng ta phải nhập gói. Sau khi chúng tôi nhập gói, đây là cách chúng tôi có thể tạo luồng đầu ra.

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

Ở đây, chúng tôi đã tạo một luồng đầu ra sẽ ghi dữ liệu vào một mảng byte với kích thước mặc định là 32 byte. Tuy nhiên, chúng ta có thể thay đổi kích thước mặc định của mảng.

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

Ở đây, kích thước chỉ định độ dài của mảng.

Các phương thức của ByteArrayOutputStream

Các ByteArrayOutputStreamlớp học cung cấp cho việc thực hiện các phương pháp khác nhau hiện diện trong OutputStreamlớp.

viết phương pháp

  • write(int byte) – writes the specified byte to the output stream
  • write(byte[] array) – writes the bytes from the specified array to the output stream
  • write(byte[] arr, int start, int length) – writes the number of bytes equal to length to the output stream from an array starting from the position start
  • writeTo(ByteArrayOutputStream out1) – writes the entire data of the current output stream to the specified output stream

Ví dụ: ByteArrayOutputStream để ghi dữ liệu

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

Đầu ra

Output stream: This is a line of text inside the string.

Trong ví dụ trên, chúng ta đã tạo một luồng đầu ra mảng byte có tên là đầu ra .

ByteArrayOutputStream output = new ByteArrayOutputStream();

Để ghi dữ liệu vào luồng đầu ra, chúng tôi đã sử dụng write()phương thức.

Lưu ý : getBytes()Phương thức được sử dụng trong chương trình chuyển đổi một chuỗi thành một mảng byte.

Truy cập dữ liệu từ ByteArrayOutputStream

  • toByteArray() – returns the array present inside the output stream
  • toString() – returns the entire data of the output stream in string form

Ví dụ,

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<byteData.length; i++) {
        System.out.print((char)byteData[i]);
      }

      // Returns a string
      String stringData = out.toString();
      System.out.println("\nData using toString(): " + stringData);

      out.close();
    }

    catch(Exception e) {
      e.getStackTrace();
    }
  }
}

Đầu ra

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

Trong ví dụ trên, chúng ta đã tạo một mảng byte để lưu trữ dữ liệu được toByteArray()phương thức trả về .

Sau đó, chúng tôi đã sử dụng vòng lặp for để truy cập từng byte từ mảng. Ở đây, mỗi byte được chuyển đổi thành ký tự tương ứng bằng cách sử dụng tính năng đánh máy.

phương thức close ()

Để đóng luồng đầu ra, chúng ta có thể sử dụng close()phương pháp.

Tuy nhiên, close()phương thức không có hiệu lực trong ByteArrayOutputStreamlớp. Chúng ta có thể sử dụng các phương thức của lớp này ngay cả sau khi close()phương thức được gọi.

Các phương thức khác của ByteArrayOutputStream

MethodsDecfscriptions
size()returns the size of the array in the output stream
flush()clears the output stream

Để tìm hiểu thêm, hãy truy cập Java ByteArrayOutputStream (tài liệu Java chính thức) .









Gõ tìm kiếm nhanh...