📜  Java IO-PipedReader(1)

📅  最后修改于: 2023-12-03 15:31:30.915000             🧑  作者: Mango

Java IO - PipedReader

PipedReader is a class in Java IO package that is used to read data from a Pipe. A Pipe is a communication channel that allows two threads to communicate with each other. One thread writes data to the Pipe and the other thread reads from the Pipe.

Creating a PipedReader

To create a PipedReader, we need to first create a Pipe and then call the reader() method of the Pipe object. Here is an example:

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

public class Main {
  public static void main(String[] args) throws IOException, InterruptedException {
    PipedReader reader = new PipedReader();
    PipedWriter writer = new PipedWriter();
    writer.connect(reader);
    // Now we can write to the Pipe using the writer object
    // And read from the Pipe using the reader object
  }
}

Here, we first create a PipedReader object reader, and a PipedWriter object writer. Then, we connect the writer to the reader using the connect() method of the PipedWriter. Once the Pipe is connected, we can start writing data to the Pipe using the writer object and read data from the Pipe using the reader object.

Reading data from a PipedReader

To read data from a PipedReader, we can use the read() method of the PipedReader. The read() method reads a single character at a time from the Pipe and returns it as an integer value.

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

public class Main {
  public static void main(String[] args) throws IOException, InterruptedException {
    PipedReader reader = new PipedReader();
    PipedWriter writer = new PipedWriter();
    writer.connect(reader);
    
    // Write data to the Pipe
    writer.write("Hello, world!".toCharArray());
    writer.close();
    
    // Read data from the Pipe
    int data;
    while ((data = reader.read()) != -1) {
      System.out.print((char) data);
    }
    reader.close();
  }
}

Here, we write the string "Hello, world!" to the Pipe using the write() method of the PipedWriter. Then, we close the writer. After that, we read data from the Pipe using the read() method of the PipedReader. The read() method returns -1 when the end of the Pipe is reached.

Conclusion

PipedReader and PipedWriter provide a simple way for two threads to communicate with each other. By creating a Pipe and connecting a PipedReader to a PipedWriter, one thread can write data to the Pipe and the other thread can read from the Pipe. PipedReader and PipedWriter are useful when we need to implement inter-thread communication in Java.