OutputStreamWriter in Java | Methods, Example

OutputStreamWriter in Java is a character output stream that translates characters into bytes. It uses a stream of bytes as its data for output.

OutputStreamWriter acts as a bridge between an incoming sequence of characters and an outgoing stream of bytes and converts a character stream into a byte stream.

When characters are written to an OutputStreamWriter, it converts them into bytes according to the default or specified character encoding and writes those bytes to the specified OutputStream.

In other words, data (characters) written to this writer are encoded into bytes using the specified character set and then writes those bytes to the specified OutputStream.

The character set guarantees that any Unicode characters that we write to the OutputStreamWriter will be encoded into the correct byte representation.

Java OutputStreamWriter class declaration


An OutputStreamWriter is a concrete subclass of Writer class that extends Object class. It is also a superclass of FileWriter class that provides a convenient way to write characters to a file.

OutputStreamWriter class implements Closeable, Flushable, Appendable, and AutoCloseable. The general syntax to declare OutputStreamWriter class in Java is as follows:

public class OutputStreamWriter
   extends Writer
         implements Closeable, Flushable, Appendable, AutoCloseable

The inheritance diagram for OutputStreamWriter class is as follows:

java.lang.Object
    java.io.Writer
        java.io.OutputStreamWriter

Constructors of OutputStreamWriter class


OutputStreamWriter class declares four constructors in Java that are as follows:

1. OutputStreamWriter(OutputStream out): This constructor creates OutputStreamWriter object that uses the default character encoding to convert characters into bytes.

The general syntax to create an object of OutputStreamWriter class in java is as follows:

OutputStreamWriter osw = new OutputStreamWriter(OutputStream out);

Here, the parameter to the constructor of OutputStreamWriter is of type OutputStream, so we can pass an object of any class derived from OutputStream to it.


2. OutputStreamWriter(OutputStream out, String charsetName): This constructor creates an OutputStreamWriter object that uses the named character encoding.

charsetName specifies the character encoding that is used to encode characters into bytes. This constructor throws an exception named UnsupportedEncodingException when named character encoding is not supported.

3. OutputStreamWriter(OutputStream out, Charset cs): This constructor creates an OutputStreamWriter object that uses the specified charset to encode characters into bytes.

4. OutputStreamWriter(OutputStream out, CharsetEncoder enc): This constructor constructs an OutputStreamWriter object that uses the specified charset encoder.

Methods of OutputStreamWriter class in Java


In addition to methods inherited from Writer class, Java OutputStreamWriter class also defines some useful methods. They are as follows:

1. void close(): This method closes the stream, flushing it first.

2. void flush(): This method flushes the stream.

3. String getEncoding(): This method returns the name of the character encoding being used by this stream.

4. void write(char[ ] cbuf, int offset, int length): This method writes a segment of an array of characters. The first parameter cbuf specifies the buffer of characters, second parameter offset specifies from where to start writing characters, and third parameter length specifies the number of characters to write into the stream.


5. void write(int c): This method writes a single character. The parameter defined in this method c of type int specifies a character to be written.

6. void write(String str, int offset, int length): This method writes a segment of a string. The parameter defined in method str represents a String, second parameter Offset specifies from where to start writing characters, and third parameter length specifies the number of characters to write into the stream.


All these methods provided by Java OutputStreamWriter class throws an exception named IOException if any error occurs.

OutputStreamWriter Example Program in Java


Let’s take a simple example program where we will write a string data into the specified file using OutputStreamWriter class. Look at the source code to understand better.

Program source code 1:

package javaPackage;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

public class OutputStreamWriterEx {
public static void main(String[] args) 
{
 String data = "I love Java Programming.";
 try 
 {
// Create a FileOutputStream object. 
     FileOutputStream file = new FileOutputStream("D:\\outputfile.txt");

// Create an OutputStreamWriter object and pass reference variable file to its constructor.
     OutputStreamWriter osw = new OutputStreamWriter(file);

// Write string to the file.
      osw.write(data);

// Close the writer.
      osw.close();
      System.out.println("Successfully written...");
 }
catch (Exception e) {
   e.getStackTrace();
 }
 }
}
Output:
           Successfully written...

Data written into the file:

I love Java Programming.

In this program, we have created an output stream using the FileOutputStream that is used to store the data in the form of individual bytes.

The FileOutputStream has been connected with the output.txt file where data is to be stored. Connecting the file outputfile.txt with FileOutputStream is done as follows:

FileOutputStream file = new FileOutputStream("D:\\outputfile.txt");

To write string data to the file, we have created an object of OutputStreamWriter class with passing reference variable file to its constructor. Then we called write() method provided by OutputStreamWriter class to write data to the file.

When we execute the above program, the outputfile.txt file is filled with the following content “I Love Java Programming”.


2. Let’s create a program to get the type of encoding that is used to write data to the output stream.

Program source code 2:

package javaPackage;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;

public class OutputStreamWriterEx {
public static void main(String[] args) 
{
 try 
 {
// Create a FileOutputStream object. 
     FileOutputStream file = new FileOutputStream("D:\\outputfile.txt");

// Create an OutputStreamWriter object with default encoding.
     OutputStreamWriter osw = new OutputStreamWriter(file);

// Create an OutputStreamWriter object with specified the encoding.
     OutputStreamWriter osw2 = new OutputStreamWriter(file, Charset.forName("UTF8"));
   
// Return the name of character encoding used by output streams.
     System.out.println("Name of character encoding used by ows: " + osw.getEncoding());
     System.out.println("Name of character encoding used by ows2: " + osw2.getEncoding());

// Closing the output stream writers.
     osw.close();
     osw2.close();
 }
catch (Exception e) {
   e.getStackTrace();
 }
 }
}
Output:
          Name of character encoding used by ows: Cp1252
          Name of character encoding used by ows2: UTF8

In this example program, we have created two output stream writer named osw and osw2.

a) osw uses the default the character encoding. Therefore, the getEncoding() method returns the default character encoding.

b) osw2 specifies the character encoding, UTF8. Therefore, the getEncoding() method returns the specified character encoding.


Note: We have called static method named forName() of Charset class to specify the type of character encoding. Charset class is used to map characters and bytes.


Hope that this tutorial has covered almost all the important points related to OutputStreamWriter class in Java with example programs. I hope that you will have understood basic concepts of OutputStreamWriter.
Thanks for reading!!!
Next ⇒ FileWriter in Java

⇐ Prev Next ⇒