Java - File Input Output Piped Stream

Introduction

Pipes can connect an input stream and an output stream.

A piped I/O is based on the producer-consumer pattern.

In a piped I/O, you create two streams representing two ends of the pipe.

PipedOutputStream object represents one end and a PipedInputStream object the other end.

You connect the two ends using the connect() method on the either object.

You can also connect them by passing one object to the constructor when you create another object.

The following code Creates piped input and output streams and connect them

PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream();
pis.connect(pos); /* Connect the two ends */

Create piped input and output streams and connect them

PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream(pis);

You produce data by using one of the write() methods of the PipedOutputStream object.

What you write automatically becomes available to the piped input stream object for reading.

You use the read() method of PipedInputStream to read data from the pipe.

The piped input stream is blocked if data is not available when it attempts to read from the pipe.

You can set the pipe capacity when you create it.

If a pipe's buffer is full, an attempt to write on the pipe will block.

// Create piped input and output streams with the buffer capacity of 2048 bytes
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pos, 2048);

The following code uses a piped I/O.

Demo

import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class Main {
  public static void main(String[] args) throws Exception {
    // Create and connect piped input and output streams
    PipedInputStream pis = new PipedInputStream();
    PipedOutputStream pos = new PipedOutputStream();
    pos.connect(pis);// ww  w.jav  a2  s  . c o  m

    // Creates and starts two threads, one to produce data (write data)
    // and one to consume data (read data)
    Runnable producer = () -> produceData(pos);
    Runnable consumer = () -> consumeData(pis);
    new Thread(producer).start();
    new Thread(consumer).start();
  }

  public static void produceData(PipedOutputStream pos) {
    try {
      for (int i = 1; i <= 50; i++) {
        pos.write((byte) i);
        pos.flush();
        System.out.println("Writing: " + i);
        Thread.sleep(500);
      }
      pos.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void consumeData(PipedInputStream pis) {
    try {
      int num = -1;
      while ((num = pis.read()) != -1) {
        System.out.println("Reading: " + num);
      }
      pis.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Result