read(): This method is available in the java.io.PipedReader class of Java.
Syntax:
int java.io.PipedReader.read() throws IOException
This method reads the next character of data from this piped stream.
If no character is available because the end of the stream has been reached, the value -1 is returned.
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 character of data, or -1 if the end of the stream is reached.
Throws:
IOException - if the pipe is broken, unconnected, closed, or an I/O error occurs.
Approach 1: When no exception
Java
import java.io.IOException;import java.io.PipedReader;import java.io.PipedWriter;public class PipedReaderread {public static void main(String[] args) throws IOException {PipedReader pipedReader = new PipedReader();PipedWriter src = new PipedWriter();pipedReader.connect(src);System.out.println("Reading");pipedReader.read();pipedReader.close();}}
Output:
Reading
Approach 2: IOException
Java
package com.PipedReader;import java.io.IOException;import java.io.PipedReader;public class PipedReaderread {public static void main(String[] args) throws IOException {PipedReader pipedReader = new PipedReader();pipedReader.read();pipedReader.close();}}
Output:
Exception in thread "main" java.io.IOException: Pipe not connected at java.base/java.io.PipedReader.read(PipedReader.java:235) at com.PipedReader.PipedReaderread.main(PipedReaderread.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