PipedReader ready() in Java

ready(): This method is available in the java.io.PipedReader class of Java.

Syntax:

boolean java.io.PipedReader.ready() throws IOException

This method tells whether this stream is ready to be read. A piped character stream is ready if the circular buffer is not empty.

Parameters: NA

Returns: True if the next read() is guaranteed not to block for input, false otherwise.

Note that returning false does not guarantee that the next read will block.

Throws:

IOException - if the pipe is broken, unconnected, or closed.

Approach 1: When no exception

Java

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

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

        PipedReader pipedReader = new PipedReader();

        PipedWriter pipedWriter = new PipedWriter();
       
        pipedReader.connect(pipedWriter);
        System.out.println(pipedReader.ready());

        pipedReader.close();

    }
}

Output:

false


Approach 2: IOException 

Java

package com.PipedReader;

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

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

        PipedReader pipedReader = new PipedReader();

        System.out.println(pipedReader.ready());

        pipedReader.close();

    }
}

Output:

Exception in thread "main" java.io.IOException: Pipe not connected at java.base/java.io.PipedReader.ready(PipedReader.java:339) at com.PipedReader.PipedReaderready.main(PipedReaderready.java:11)


Some other methods of PipedReader

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

connect(PipedWriter): This method causes this piped reader to be connected to the piped writer src.

PipedReader(): This method creates a PipedReader so that it is not yet connected. It must be connected to a PipedWriter before being used.

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

PipedReader(PipedWriter): This method creates a PipedReader so that it is connected to the piped writer src.

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

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

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

ready(): This method tells whether this stream is ready to be read.

No comments:

Post a Comment