< Prev
Next >


OutputStreamWriter class is a subclass of Writer abstract class. Using OutputStreamWriter class, we can convert a character, character arrays or a String to bytes before it is written to an output stream. Hence, OutputStreamWriter class acts as a converter of characters to bytes.

Constructor :

OutputStreamWriter(OutputStream is)
This constructor creates an OutputStreamWriter object wrapped around an OutputStream to write data to this OutputStream in the form of bytes.


char arr[] ={'a', 'b', 'c', 'd'};

FileOutputStream fos = new FileOutputStream("D://TextBook.txt");
OutputStreamWriter osr = new OutputStreamWriter (fos);
In this example, FileOutputStream is wrapped inside OutputStreamWriter. We can only write bytes through FileOutputStream, hence, OutputStreamWriter class will first convert the characters in a character array, arr, to bytes before writing them to a file TextBook.txt using FileOutputStream.

Point to remember

FileOutputStream is a subclass of OutputStream

Methods for writing using OutputStreamWriter

Some methods that we generally use while working with CharArrayWriter are shown in the table below :

Methods Description
This method flushes any data to be written out of this character output stream.
write(int c)
This method writes one character at a time to this character output stream's buffer.

This method writes a whole character array at a time to this character output's buffer.

write(String str)
This method writes a String to this character output stream's buffer.

This method closes this output stream and also frees any resources connected with this output stream.

Writing a character array and a String to a file using OutputStreamWriter.

We are writing to a file called TextBook.txt using its path D:\\TextBook.txt.
// Program to write a character array and a String using OutputStreamWriter.

import java.io.*;

class A
public static void main(String... ar)

String str="Hello World";
char[] arr= {'a', 'b', 'c' , 'd' , 'e'};

FileOutputStream fos= new FileOutputStream("D:\\TextBook.txt"); 
OutputStreamWriter osw= new OutputStreamWriter(fos); 

// writing each character of character array using for-each loop
for(char c : arr)

//writing a String

catch(IOException e)

Output is -:

After the execution of this program, a file TextBook.txt is created in the D: drive, with contents -:
abcdeHello World

Program Analysis

Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter

< Prev
Next >
< InputStreamReader

Please Subscribe

Please subscribe to our social media channels for daily updates.

Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page