PipedWriter

posted in: Java | 0

PipedWriter:—           

             The Java.io.PipedWriter piped character-output streams.

Syntax for PipedWriter Class declaration:

The declaration of java.io.PipedWriter class is as follows:

               public class PipedWriter extends Writer

PipedWriter

Indexes of PipedWriter:

            There are three fields for Java.io.PipedWriter. They are:

                               1)    Variable index

                               2)    Constructor index

                               3)    Method index

1)    Variable Index:

          There is a field inherited from class java.io. PipedWriter. It is:

  • lock — This is the object used to synchronize operations on this stream.

 2)    Constructor Index:

There are two constructors defined in the PipedWriter class. They are as follows:

                     i)  PipedWriter () – Creates a pipedwriter that is not yet connected to a piped reader.

                     ii)  PipedWriter (PipedReader snk) – Creates a piped writer connected to the specified piped reader.

3)   Method Index:

  • There are five methods defined in the PipedWriter class. They are as follows:
  1. close()- closes the piped output stream and releases any system resources associated with this stream.
  2. connect(PipedWriter)- flush the stream.
  3. write(char [], int, int)-Writes a portion of an array of characters.
  4. write(int)- writes a single character.
  5. flush() – writes a portion of a string.
  • The methods are also inherited from the following classes:
  1. Java.io.Writer
  2. Java.lang.Object

 Variables:

1)    Lock: This object of PipedWriter is used to synchronize operations on this stream.

Syntax:

               protected Object lock

Constructors:

1)      PipedWriter ()

Syntax:

               public PipedWriter()

Description:

PipedWriter () constructor creates a piped writer that is not yet connected to a piped reader. It must be connected to a piped reader, either by the receiver or the sender, before being used.

2)      PipedWriter (PipedReader snk)

Syntax:                

               public PipedWriter(PipedReader snk)throws IOException
  • snk – The piped reader to connect to.
  • IOException – if an I/O error occurs.

Description:

 

PipedWriter(PipedReader snk) constructor creates a piped writer connected to the specified piped reader. Data characters written to this stream will then be available as input from snk.

Methods:

1)    connect(PipedReader)-

Syntax:

                public void connect(PipedReader snk) throws IOException
  • snk – the piped reader to connect to.
  • IOException – if an I/O error occurs.

Descrpition:

  • Connects this pipedwriter to a receiver. If this object is already connected to some other piped reader, an IOException is thrown.
  • If snk is an unconnected piped reader and src is an unconnected piped writer, they may be connected by either the call:

“src.connect(snk)” or “snk.connect(src)” (the two calls have the same effect.)

2)    write(char [], int, int)-

Syntax:

               public void write(char[] cbuf,int off,int len)throws IOException
  • cbuf – the data.
  • off – the start offset in the data.
  • len – the number of characters to write.
  • IOException – if the pipe is broken, unconnected, closed or an I/O error occurs.

Description:

Writes len characters from the specified character array starting at offset off to this piped output stream. This method blocks until all the characters are written to the output stream. If a thread was reading data characters from the connected piped input stream, but the thread is no longer alive, then an IOException is thrown. It is specified by write in class Writer.

3)    Write(int)

Syntax:

               public void write(int c)throws IOException
  • c – the char to be written.
  • IOException – if the pipe is broken, unconnected, closed or an I/O error occurs.

 Description:

  • Writes the specified char to the piped output stream. If a thread was reading data characters from the connected piped input stream, but the thread is no longer alive, then anIOException is thrown.
  • Implements the write method of Writer.

4)    flush()

Syntax:

               public void flush() throws IOException

IOException – If the pipe is closed, or an I/O error occurs

Description:

  • Flushes this output stream and forces any buffered output characters to be written out. This will notify any readers that characters are waiting in the pipe.
  • It is specified by flush in interface Flushable and flush in class Writer.

5)    close():

Syntax:

               public void close( )throws IOException
  • IOException – If an I/O error occurs

Description:

  • Closes this piped output stream and releases any system resources associated with this stream. This stream may no longer be used for writing characters.
  • It is specified by close in interface Closeable, close in interface AutoCloseable and close in class Writer.

Methods inherited from java.io.Writer:

   i)  append(char)

   ii)  append(CharSequence)

   iii)  append(CharSequence, int, int)

   iv)  write(char[])

   v)  write(String)

 i)  append(char):

Syntax:

               Public Writer append (char c) throws IOException
  • c – The 16-bit character to append.
  • IOException – If an I/O error occurs.

Description:

Appends the specified character to this writer. An invocation of this method of the form out.append(c) behaves in exactly the same way as the invocation out.write(c). It is specified by “append in interface Appendable”. It returns the Writer.

ii)  append(CharSequence)

Syntax:

         public Writer append (CharSequence csq) throws IOException
  • csq – The character sequence to append. If csq is null, then the four characters “null” are appended to this writer.
  • IOException – If an I/O error occurs

Description:

  •  Appends the specified character sequence to this writer. An invocation of this method of the form out.append(csq) behaves in exactly the same way as the invocation out.write(csq.toString()).
  •  Depending on the specification of toString for the character sequence csq, the entire sequence may not be appended. For instance, invoking the toString method of a character buffer will return a subsequence whose content depends upon the buffer’s position and limit. 
  • It is specified by “append in interface Appendable”. It returns the Writer.

iii)  append(CharSequence, int, int)

Syntax:

public Writer append (CharSequence csq, int start, int end) throws IOException
  • csq – The character sequence from which a subsequence will be appended. If csq is null, then characters will be appended as if csq contained the four characters “null”.
  • start – The index of the first character in the subsequence
  • end – The index of the character following the last character in the subsequence
  • IndexOutOfBoundsException – If start or end are negative, start is greater than end, or end is greater than csq.length().
  • IOException – If an I/O error occurs

Description:

  • Appends a subsequence of the specified character sequence to this writer.Appendable. An invocation of this method of the form out.append(csq, start, end) when csq is not null behaves in exactly the same way as the invocation out.write(csq.subsequence(start, end).toString()).
  • It is specified by “append in interface Appendable”. It returns the Writer

iv)  write(char[ ]):

Syntax:

         public void write(char[] cbuf)throws IOException
  • cbuf – Array of characters to be written
  • IOException – If an I/O error occurs

Description:

Writes an array of characters.

v)  write(String)

Syntax:

    public void write(String str)throws IOException
  • str – String to be written
  • IOException – If an I/O error occurs

Description:

Writes a string.

Methods inherited from class java.lang.Object

      i)  clone()

      ii)  equals()

      iii)  finalize()

      iv) getClass()

      v)  hashCode()

      vi) notify()

      vii) notiftAll()

      viii) toString()

      ix)  wait(…)

      x)  wait(,,,)

     xi)  wait(—)

i)  clone():–

Syntax:

    protected object clone() throws CloneNotSupportedException
  • CloneNotSupportedException – if the object’s class does not support the Cloneable interface. Subclasses that override the clone method can also throw this exception to indicate that an instance cannot be cloned.

Description:

Creates and returns a copy of this object. The precise meaning of “copy” may depend on the class of the object. Returns a clone of this sentence.

ii)  equals():–

Syntax:

public boolean equals (Object obj)
  • obj – the reference object with which to compare, true if this object is the same as the obj argument; false otherwise.

Description:

Indicates whether some other object is “equal to” this one. The equals method implements an equivalence relation on non-null object references.

iii) finalize():–

Syntax:

           protected void finalize() throws Throwable
  • Throwable – the Exception raised by this method

Description:

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.

iv)  getClass():–

Syntax:

    public final Class <?> getClass()

Description:

Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class. It returns the Class object that represents the runtime class of this object.

v)  hashCode():–

Syntax:

             public int hashCode()

Description:

Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by ashMap. It returns a hash code value for this object.

vi)  notify():–

Syntax:

            public final void notify()

Description:

Wakes up a single thread that is waiting on this object’s monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object’s monitor by calling one of the wait methods.

Throws:

  • IllegalMonitorStateException – if the current thread is not the owner of this object’s monitor.

vii)  notifyAll():–

Syntax:

            public final void notifyAll()

Description:

Wakes up all threads that are waiting on this object’s monitor. A thread waits on an object’s monitor by calling one of the wait methods.

Throws:

  • IllegalMonitorStateException – if the current thread is not the owner of this object’s monitor.

viii)  toString():–

Syntax:

public String toString()

Description:

Returns a string representation of the object. In general, the toString() method returns a string that “textually represents” this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.It returns a string representation of the object.

xi)  wait():–

Syntax:

public final void wait() throws InterruptedException
  • IllegalMonitorStateException – if the current thread is not the owner of the object’s monitor.
  • InterruptedException – if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.

Description:

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

x)  wait(long):–

Syntax:           

            public final void wait(long timeout) throws InterruptedException
  • timeout – the maximum time to wait in milliseconds.
  • IllegalArgumentException – if the value of timeout is negative.
  • IllegalMonitorStateException – if the current thread is not the owner of the object’s monitor.
  • InterruptedException – if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.

Description:

Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

xi)  wait(long, int):–

Syntax:

      public final void wait(long timeout, int nanos) throws InterruptedException
  • timeout – the maximum time to wait in milliseconds.
  • nanos – additional time, in nanoseconds range 0-999999.
  • IllegalArgumentException – if the value of timeout is negative or the value of nanos is not in the range 0-999999.
  • IllegalMonitorStateException – if the current thread is not the owner of this object’s monitor.
  • InterruptedException – if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.

Description:

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

Example:

1)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedReader;
import java.io.PipedWriter;
public class PipedWriterExp {
       public static void main(String args[]) throws IOException{
        final PipedReader reader = new PipedReader();
        final PipedWriter writer = new PipedWriter(reader);
        final Thread readerThread = new Thread(new ReaderThread(writer));
        final Thread writerThread = new Thread(new WriterThread(reader));
        readerThread.start();
        writerThread.start();
      }

}
class ReaderThread implements Runnable{
PipedWriter writer;
 public ReaderThread(PipedWriter writer){
 this.writer = writer;
 }
 public void run() {
 final InputStreamReader streamReader = new InputStreamReader(System.in);
 final BufferedReader bufferedReader = new BufferedReader(streamReader);
 try {
 while (true) {
String line = bufferedReader.readLine();
 writer.write(line);
 }
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
}
 class WriterThread implements Runnable{
PipedReader reader;
 public WriterThread(PipedReader reader){
 this.reader = reader;
 }
 public void run() {
 while(true){
 try {
 char c;
 while( (c = (char)reader.read()) != -1){
 System.out.print(c);
 } 
} catch (IOException e) {
 e.printStackTrace();
 }
 }
 }
}

It read from the console and redirect console input to another thread using piped character stream.

 

 

 

Leave a Reply