OutputStream trong java

OutputStream là một abstract class đại diện cho một luồng dữ liệu đầu ra dạng byte có thứ tự. Hay nói cách khác bạn có thể truyền dữ liệu từ OutputStream theo một chuỗi byte có thứ tự. Điều này sẽ giúp ích khi chúng ta ghi dữ liệu vào file hoặc qua network.

OutputStream method

OutputStream là một abstract class chứa các method giúp thao tác ghi dữ liệu như:

void close(): Đóng output stream, giải phóng tất cả các tài nguyên đang được kết nối với luồng này.

void flush(): Xoá dữ liệu đang được lưu trong output stream và buộc nó ghi dữ liệu xuống điểm đích.

void write(byte[] b): Ghi b.length byte từ mảng byte tham số vào output stream.

void write(byte[], int offset, int length): Ghi Ghi length byte từ mảng byte tham số vào output stream bắt đầu tại vị trí offset trong mảng.

abstract void write(int b): Ghi byte b được chỉ định trong tham số truyền vào xuống outputstream.

import java.io.*; 
//Java program to demonstrate OutputStream 
class OutputStreamDemo 
{ 
    public static void main(String args[])throws Exception 
    { 
        OutputStream os = new FileOutputStream("file.txt"); 
        byte b[] = {65, 66, 67, 68, 69, 70}; 
          
        //illustrating write(byte[] b) method 
        os.write(b); 
          
        //illustrating flush() method 
        os.flush(); 
  
        //illustrating write(int b) method 
        for (int i = 71; i <75 ; i++)  
        { 
            os.write(i); 
        } 
          
        os.flush(); 
          
        //close the stream 
        os.close(); 
    } 
}

Output: ABCDEFGHIJ

Hiệu suất

Việc ghi dữ liệu với mảng byte vào outputstream sẽ nhanh hơn so với bạn ghi từng byte đơn vào outputstream. Vì vậy cố gắng sử dụng write(byte[]) hoặc write(byte[] b, int off, int len) thay write(int b).

Nguồn tham khảo:

https://www.geeksforgeeks.org/java-io-outputstream-class-java/

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x