Tags:

Luồng dữ liệu ngầm PipedReader và PipedWriter

PipedReader và PipedWriter là các luồng dữ liệu đầu vào và đầu ra dạng ký tự ,cung cấp khả năng giao tiếp giữa 2 luồng chạy trên cùng JVM.

Giả sử bạn có 2 luồng, A là luồng dữ liệu đầu vào và B là luồng dữ liệu đầu ra. Hai luồng này chạy trên 2 thread khác nhau vậy làm sao để kết nối A và B lại với nhau?

Trong java cung cấp 2 class PipedReader đại diện cho luồng dữ liệu đầu vào và PipedWriter đại diện cho luồng dữ liệu đầu ra, chúng có thể kết nối với nhau và tự hiểu ngầm ra “tao ghi dữ liệu cho mày – Tao đọc dữ liệu từ mày”.

import java.io.*;

class PipeExample {

    public static void main(String[] args) throws IOException {

        final PipedReader reader = new PipedReader();
        final PipedWriter writer  = new PipedWriter(reader);


        Thread thread1 = new Thread(() -> {
            try {
                writer.write("Hello world, pipe!");
            } catch (IOException e) {
            }
        });


        Thread thread2 = new Thread(() -> {
            try {
                System.out.println("I'm thread 2");
                int data = reader.read();
                while(data != -1){
                    System.out.print((char)data);
                    data = reader.read();
                }
            } catch (IOException e) {
            }
        });

        thread1.start();
        thread2.start();

    }
}

connect() trong PipedReader và PipedWriter 

Trong trường hợp tại thời điểm khởi tạo chúng ta chưa xác định điểm PipedReader và PipedWriter nào sẽ kết nối với nhau thì chúng ta có thể sử dụng method conect() để liên kết chúng lại với nhau. 

Note: Cả PipedReader và PipedWriter đều có method connect() chúng ta có thể sử dụng một trong hai đều có tác dụng như nhau. 

import java.io.*;

class PipeExample {

    public static void main(String[] args) {

        PipedReader input = new PipedReader();
        PipedWriter output = new PipedWriter();
        try {
            // Use of connect() : connecting input with output
//            output.connect(input);
            input.connect(output);

            output.write(65);
            output.write(66);
            output.write(67);
            output.write(68);
            output.write(69);
            output.write(70);


            // Use of read(char[] buffer, int offset, int maxlen) :
            char[] buffer = new char[5];
            // destination 'buffer'
            input.read(buffer, 0, 5);

            String str = new String(buffer);
            System.out.println("Using read(buffer, offset, maxlen) : " + str);

            // USe of close() method :
            System.out.println("Closing the stream");

        } catch (IOException excpt) {
            excpt.printStackTrace();
        } finally {
            try {
                input.close();
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Output:

Using read(buffer, offset, maxlen) : ABCDE
Closing the stream

Các method trong PipedReader

PipedReader đại diện cho luồng dữ liệu đầu vào chứa các method phục vụ cho việc đọc dữ liệu từ PipedWriter.

int read() – Đọc byte tiếp theo từ PipedReader. Giá trị byte nằm trong khoảng 0 – 255. Trả về -1 để thông báo rằng đã đọc hết dữ liệu trong PipedReader.

int read(char[] buffer, int offset, int maxlen) – Đọc dữ liệu từ PipedInputStream bắt đầu tại vị trí offset và đọc tối đa maxlen.

public int read(char[] buffer, int offset, int maxlen)
Parameters : 
buffer : Nơi chứa dữ liệu được đọc vào
offset : Vị trí đầu tiên được lưu trữ trong buffer
maxlen : Số lượng ký byte tối đa được đọc
Return : Trả về số lượng byte đọc được                                               
return -1 Nếu không còn dữ liệu để đọc 

> IOException : Trong trường hợp xảy ra lỗi IO.
-> NullPointerException : Nếu buffer rỗng
-> IndexOutOfBoundsException : Nếu offset âm hoặc maxlen > b.length - offset
import java.io.*;

class PipeExample {

    public static void main(String[] args) {

        PipedReader input = new PipedReader();
        PipedWriter output = new PipedWriter();
        try {
            // Use of connect() : connecting input with output
            input.connect(output);

            output.write(65);
            output.write(66);
            output.write(67);
            output.write(68);
            output.write(69);
            output.write(70);

            // Use of read(byte[] buffer, int offset, int maxlen) :
            char[] buffer = new char[5];
            // destination 'buffer'
            input.read(buffer, 2, 2);

            String str = new String(buffer);
            System.out.println("Using read(buffer, offset, maxlen) : " + str);

            input.close();

        } catch (IOException excpt) {
            excpt.printStackTrace();
        } finally {
            try {
                input.close();
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

Output: Using read(buffer, offset, maxlen) : __AB_

Sau khi mình chọn offset là 2 thì 2 vị trí đầu tiên của mảng rỗng, và đọc tối đa maxlen là 2 ký tự AB.

void close() – Đóng các kết nối của PipedInputStream đến các tài nguyên mà nó đang tham chiếu đến.

void close() – Đóng các kết nối của PipedReader đến các tài nguyên mà nó đang tham chiếu đến.

Các method trong PipedWriter

PipedWriter đại diện cho luồng dữ liệu đầu ra chứa các method phục vụ cho ghi dữ liệu vào PipedReader.

void write(int byte) – Ghi dữ liệu từng byte vào PipedReader.

void write(char[] buffer, int offset, int maxlen) – Ghi tối đa maxlen byte bắt đầu từ vị trí offsert trong mảng buffer vào PipedOutStream.

void write(String s, int offset, int maxlen) – Ghi chuỗi con của chuỗi s bắt đầu từ vị trí offset trong mảng buffer xuống PipedReader.

void write(char[] b) – Ghi một mảng ký tự vào PipedReader.

void write(String s) – Ghi một chuỗi vào PipedReader.

import java.io.*;

class PipeExample {

    public static void main(String[] args) {

        PipedReader input = new PipedReader();
        PipedWriter output = new PipedWriter();
        try {
            // Use of connect() : connecting input with output
            input.connect(output);

            output.write(65);
            output.write("\nhello");
            output.write("share", 1, 2);
            char[] chars = new char[7];
            chars[0] = 'w';
            chars[1] = 'e';
            chars[2] = 'l';
            chars[3] = 'c';
            chars[4] = 'o';
            chars[5] = 'm';
            chars[6] = 'e';

            output.write(chars);
            output.write(chars, 0, 3);

            int data = input.read();
            while (data != -1) {
                System.out.print((char) data);
                data = input.read();
            }

            input.close();

        } catch (IOException excpt) {
            excpt.printStackTrace();
        } finally {
            try {
                input.close();
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Output:

A
hellohawelcomewel

void close() – Đóng kết nối giữa PipedWriter với các tài nguyên khác.

void connect(PipedReader input) – Kết nối PipedWriter với PipedReader.

void flush() – Đẩy dữ liệu xuống PipedReader. Trong trường hợp bạn write() dữ liệu xuống vì các mục đích khác nhau như hiệu xuất etc mà dữ liệu chưa được ghi xuống PipedReader, sử dụng flush() để đẩy dữ liệu xuống

import java.io.*;

class PipeExample {

    public static void main(String[] args) throws IOException {
        PipedReader input = new PipedReader();
        PipedWriter output = new PipedWriter();
        try {
            // Use of connect() : connecting geek_input with geek_output
            input.connect(output);

            // Use of write(int byte) :
            output.write(65);
            output.write(66);
            output.write(67);
            output.write(68);
            output.write(69);

            // Use of flush() method :
            output.flush();
            System.out.println("Use of flush() method : ");

            int i = 5;
            while (i > 0) {
                System.out.print(" " + (char) input.read());
                i--;
            }

            // USe of close() method :
            System.out.println("\nClosing the Output stream");
            output.close();

        } catch (IOException excpt) {
            excpt.printStackTrace();
        } finally {
            try {
                input.close();
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

Output:

Use of flush() method :
A B C D E
Closing the Output stream

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