PipedInputStream read() in Java

read(): This method is available in the java.io.PipedInputStream class of Java.

Syntax:

int java.io.PipedInputStream.read() throws IOException

This method reads the next byte of data from this piped input stream.

The value byte is returned as an int in the range 0 to 255. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

Parameters: NA

Returns: the next byte of data, or -1 if the end of the stream is reached.

Throws:

IOException - if the pipe is unconnected, broken, closed, or if an I/O error occurs.

Approach 1: When no exception

Java

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

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

        PipedInputStream pipedInputStream =
new PipedInputStream();

        PipedOutputStream src = new PipedOutputStream();

        pipedInputStream.connect(src);
        System.out.println(pipedInputStream.read());
        pipedInputStream.close();

    }
}

Output:

-1


Approach 2: IOException

Java

package com.PipedInputStream;

import java.io.IOException;
import java.io.PipedInputStream;

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

        PipedInputStream pipedInputStream =
new PipedInputStream();

        System.out.println(pipedInputStream.read());
        pipedInputStream.close();

    }
}

Output:

Exception in thread "main" java.io.IOException: Pipe not connected at java.base/java.io.PipedInputStream.read(PipedInputStream.java:305) at com.PipedInputStream.PipedInputStreamread.main(PipedInputStreamread.java:11)


Some other methods of PipedInputStream

close(): This method closes this piped input stream and releases any system resources associated with the stream.

connect(PipedOutputStream): This method causes this piped input stream to be connected to the piped output stream src.

available(): This method returns the number of bytes that can be read from this input stream without blocking.

PipedInputStream(): This method creates a PipedInputStream so that it is not yet connected.

PipedInputStream(int): This method creates a PipedInputStream so that it is not yet connected and uses the specified pipe size for the pipe's buffer.

PipedInputStream(PipedOutputStream): This method creates a PipedInputStream so that it is connected to the piped output stream src.

PipedInputStream(PipedOutputStream, int): This method creates a PipedInputStream so that it is connected to the piped output stream src and uses the specified pipe size for the pipe's buffer.

read(): This method reads the next byte of data from this piped input stream.

read(byte[], int, int): This method reads up to len bytes of data from this piped input stream into an array of bytes.

No comments:

Post a Comment