37. ByteArrayOutputStream trong lập trình java

Trong lập trình Java, ByteArrayOutputStream là một lớp con của OutputStream, nó được sử dụng để ghi dữ liệu vào một mảng byte như một nguồn dữ liệu đầu ra (output stream). ByteArrayOutputStream cho phép bạn ghi dữ liệu vào một mảng byte mà không cần tạo tệp thực tế hoặc kết nối mạng.

Với ByteArrayOutputStream, bạn có thể ghi dữ liệu nhị phân vào một mảng byte và sau đó sử dụng mảng này để thực hiện các tác vụ khác, như lưu trữ dữ liệu, chuyển đổi dữ liệu, v.v.

Dưới đây là cú pháp của lớp ByteArrayOutputStream:

java
public class ByteArrayOutputStream extends OutputStream {
    // Constructors:
    public ByteArrayOutputStream()
    public ByteArrayOutputStream(int size)

    // Methods:
    public void write(int b)
    public void write(byte[] b, int off, int len)
    public void writeTo(OutputStream out) throws IOException
    public void reset()
    public byte[] toByteArray()
    public int size()
    public String toString()
    public String toString(String charsetName) throws UnsupportedEncodingException
    public void close()
}

Một số phương thức quan trọng của ByteArrayOutputStream:

  • write(int b): Ghi một byte vào ByteArrayOutputStream.
  • write(byte[] b, int off, int len): Ghi mảng byte b bắt đầu từ vị trí off và có độ dài len vào ByteArrayOutputStream.
  • writeTo(OutputStream out): Ghi tất cả dữ liệu trong ByteArrayOutputStream vào một OutputStream khác.
  • reset(): Đặt lại ByteArrayOutputStream về trạng thái ban đầu, xóa tất cả dữ liệu trong luồng.
  • toByteArray(): Trả về một mảng byte chứa tất cả dữ liệu đã ghi vào ByteArrayOutputStream.
  • size(): Trả về kích thước của ByteArrayOutputStream (tổng số byte đã ghi vào).
  • toString(): Chuyển đổi nội dung của ByteArrayOutputStream thành một chuỗi sử dụng bộ mã hóa mặc định của hệ thống.
  • toString(String charsetName): Chuyển đổi nội dung của ByteArrayOutputStream thành một chuỗi sử dụng bộ mã hóa được chỉ định.

Dưới đây là một ví dụ minh họa về việc sử dụng ByteArrayOutputStream:

java
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ByteArrayOutputStreamExample {
    public static void main(String[] args) {
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            // Ghi dữ liệu vào ByteArrayOutputStream
            byteArrayOutputStream.write("Hello, this is an example.".getBytes());

            // Lấy mảng byte chứa dữ liệu đã ghi
            byte[] data = byteArrayOutputStream.toByteArray();

            // In ra dữ liệu từ mảng byte
            System.out.println(new String(data));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output sẽ là: “Hello, this is an example.”.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top