Home » Java programming language

Java PipedInputStream receive() Method with Example

PipedInputStream Class receive() method: Here, we are going to learn about the receive() method of PipedInputStream Class with its syntax and example.
Submitted by Preeti Jain, on April 17, 2020

PipedInputStream Class receive() method

  • receive() method is available in java.io package.
  • receive() method is used to receive a byte of content and it will block when no more input remains.
  • receive() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • receive() method may throw an exception at the time of receiving a byte of data.
    IOException: This exception may throw when getting any input/output error or pipe not connected properly, or stream closed.

Syntax:

    protected void receive(int byt);

Parameter(s):

  • int byt – represents the byte getting received.

Return value:

The return type of the method is void, it returns nothing.

Example:

// Java program to demonstrate the example 
// of receive(int byt) method of PipedInputStream

import java.io.*;

public class ReceiveOfPIS extends PipedInputStream {
    public static void main(String[] args) throws Exception {
        int val = 65;
        
        try {
            // Instantiates ReceiveOfPIS and 
            // PipedOutputStream
            ReceiveOfPIS pipe_in = new ReceiveOfPIS();
            PipedOutputStream pipe_out = new PipedOutputStream();

            // By using connect() method is to
            // connect this pipe_in to the given pipe_out
            pipe_in.connect(pipe_out);

            for (int i = 0; i < 3; ++i) {
                // By using write() method is to
                // write the val to the stream pipe_out
                pipe_out.write(val);
                val++;
            }

            for (int i = 1; i < 4; ++i) {
                // By using receive() method is to
                // receive a byte
                pipe_in.receive(val);
                System.out.println(i + " " + "Byte Received ");
            }

            // By using close() method is to close
            // the stream
            pipe_in.close();
            pipe_out.close();
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }
}

Output

1 Byte Received 
2 Byte Received 
3 Byte Received 


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.