OutputStreamWriter

posted in: Java | 0

OutputStreamWriter –

  • An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset.
  • The charset that it uses may be specified by name or may be given explicitly, or the platform’s default charset may be accepted.
  • Each invocation of a write() method causes the encoding converter to be invoked on the given character(s).
  • The resulting bytes are accumulated in a buffer before being written to the underlying output stream. The size of this buffer may be specified, but by default it is large enough for most purposes.
  • Note: The characters passed to the write() methods are not buffered.
  • To avoid frequent converter invocations, consider wrapping an OutputStreamWriter within a BufferedWriter . For example:
Writer out = new BufferedWriter(new OutputStreamWriter(System.out)); 

OutputStreamWriter
Important Terms:

1.      Surrogate Pair:

  • surrogate pair is a character represented by a sequence of two char values: A high surrogate in the range ‘\uD800’ to ‘\uDBFF’ followed by a low surrogate in the range ‘\uDC00’ to ‘\uDFFF’.

2.      Malformed Surrogate element:

  • malformed surrogate element is a high surrogate that is not followed by a low surrogate or a low surrogate that is not preceded by a high surrogate.
  • This class always replaces malformed surrogate elements and unmappable character sequences with the charset’s default substitution sequence. The “CharsetEncoder” class should be used when more control over the encoding process is required.

Indexes of OutputStreamWriter:

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

1) Variable index

2) Constructor index

3) Method index

1)      Variable Index:

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

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

2)      Constructor Index:

There are four constructors defined in the OutputStreamWriter class. They are as follows:                                         

             1)      OutputStreamWriter (OutputStream out)                                                     

             2)      OutputStreamWriter (OutputStream out, Charset cs)         

             3)      OutputStreamWriter (OutputStream out, CharsetEncoder enc)  

             4)      OutputStreamWriter (OutputStream out, String charsetName)

3)      Method Index:

  • There are five methods defined in the OutputStreamWriter class. They are as follows:

             1)      close – Closes the stream, flushing it first.

             2)      flush() –  Flushes the stream.

             3)      getEncoding – Returns the name of the character encoding being used in stream.

             4)      write(char[] cbuf, int off, int len) – Writes a portion of an array of characters.

             5)      write(int c) – Writes a single character.

             6)      write(String str, int off, int len) – Writes a portion of a string.

  • The methods are also inherited from the following classes:

                   1.       Java.io.Writer
                   2.       Java.lang.Object

Variables:

  • lock: The object used to synchronize operations on this stream.

Syntax:

               protected Object lock

Constructors:

1.      OutputStreamWriter(OutputStream, String):

Creates an OutputStreamWriter that uses the named charset.

Syntax:

   public OutputStreamWriter(OutputStream out,String charsetName) throws 
                                                       UnsupportedEncodedException
  • out – An OutputStream
  • charsetName – The name of a supported charset.
  • UnsupportedEncodedException – If the named encoding is not supported

 2.      OutputStreamWriter(OutputStream)

Creates an OutputStreamWriter that uses the default character encoding.

Syntax:

               public OutputStreamWriter(OutputStream out)
  • out – An OutputStream

3.      OutputStreamWriter(OutputStream, Charset)

Creates an OutputStreamWriter that uses the given charset.

Syntax:

               public OutputStreamWriter(OutputStream out, Charset cs)
  • out – An OutputStream
  • cs – A charset

4.      OutputStreamWriter(OutputStream, CharsetEncoder)

Creates an OutputStreamWriter that uses the given charset encoder.

Syntax:

               public OutputStreamWriter(OutputStream out, CharsetEncoder enc)
  • out – An OutputStream
  • enc – A charset encoder

Methods:

1)      getEncoding()-

Syntax:

               public String getEncoding()

Descrpition:

  • If the encoding has an historical name then that name is returned; otherwise the encoding’s canonical name is returned.
  • If this instance was created with the OutStreamWriter(OutputStreamWriter, String)  constructor then the returned name, being unique for the encoding, may differ from the name passed to the constructor. This method may return null if the stream has been closed.
  • Returns the name of the character encoding being used by this stream.

Returns:

The historical name of this encoding, or possibly null if the stream has been closed

2)      write(int)-

Syntax:

               public void write (int c) throws IOException
  • c – int specifying a character to be written
  • IOException – If an I/O error occurs

Description:

  • Writes a single character.
  • It overrides “write” in class Writer

3)      Write(char[], int, int)

Syntax:

               public void write(char[] cbuf, int off, int len)throws IOException
  • cbuf – Buffer of characters
  • off – Offset from which to start writing characters
  • len – Number of characters to write
  • IOException – If an I/O error occurs

Description:

  • Writes a portion of an array of characters.
  • It is specified by write in class Writer.

4)      Write(String, int, int)

Syntax:

               public void write(String str, int off, int len)throws IOException 
  • str – A String
  • off – Offset from which to start writing characters
  • len – Number of characters to write
  • IOException – If an I/O error occurs

Description: Writes a portion of a string. It overrides write in class Writer

5)      flush()

Syntax:

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

Description:

  • Flushes the stream.
  • It is specified by flush in interface Flushable and flush in class Writer.

6)   close()

Syntax:

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

Descrpition:

  • Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect.
  • It is specified by close in interface Closeable and close in class Writer

Methods inherited from class java.io.Writer

                i)   append(…)

               ii)   append(—)

               iii)  append(,,,)

               iv)  writer(…)

               v)   writer(—)

i)  append(…):

Appends the specified character to this writer.

Syntax:

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

ii)  append(—):

Appends the specified character sequence to this writer.

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

iii)  append(,,,):

Appends a subsequence of the specified character sequence to this “writer.Appendable”.

Syntax:

          public Writer append(CharSequence csq, int start, int end) throws                                                   IOException, IndexOutOfBoundsException
  • 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

iv)  write(…):

Writes an array of characters.

Syntax:

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

v)  write(—):

Writes a string.

Syntax:

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

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 Cloeanable 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 HashMap.

It returns a hash code value for this object.

vi)  notify():–

               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():–

               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():–

               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.

ix)  wait(…):–

               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(,,,):–

               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(—):–

       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.OutputStreamWriter;
import java.io.OutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class JavaOutputStreamWriterExample{
   public static void main(String args[]){
     OutputStreamWriter ow = null;
     OutputStream os = null;
     File opFile = null;
     String str1 = "Researchers Hub, ";
     String str2 = "OutputStramWriter.";
     try{
       opFile = new File("D:/work//osw.txt");
       os = new FileOutputStream(opFile);
       ow = new OutputStreamWriter(os);
       System.out.println("Writing data in file..!!");
       ow.write(str1); 
       ow.append(str2);
       System.out.println("Data successfully written in file..!!");
    }
    catch(IOException e){
       System.out.println("Exception caught..!!");
       e.printStackTrace();
    }
    finally{
       try{
         System.out.println("Flushing object..!!");
         outStream.flush();
         osWriter.flush();
         System.out.println("Closing object..!!");
         outStream.close();
         osWriter.close();
      }
      catch(IOException ioe){
         System.out.println("IOException caught..!!");
         ioe.printStackTrace();
   }
  }
 }
}

Output:-

Writing data in file..!!
 Data successfully written in file..!!
 Flushing object..!!
 Closing object..!!

osw.txt is as follows:

Researchers Hub, OutputStreamWriter.

 

 

 

 

Leave a Reply