Tuesday, October 16, 2012

Java OutputStreamWriter example

Java OutputStreamWriter

Java OutputStreamWriter is useful in encoding a character streams to byte streams. The bytes are encoded using the specified charset. It can use a user defined charset or system’s default charset. We must wrap OutputStreamWriter within a java BufferedWriter class, it is a good practice and it also improves program efficiency.
This class has 4 constructors as follows,
  1. OutputStreamWriter(OutputStream out)
  2. OutputStreamWriter(OutputStream out, Charset cs)
  3. OutputStreamWriter(OutputStream out, CharsetEncoder csencode)
  4. OutputStreamWriter(OutputStream out, String charsetname)
The first constructor accepts only single parameter i.e. object of a java OutputStream class and it uses the system’s default charset. The second constructor accepts two parameters one object of OutputStream and charset. The other two constructors also accept two parameters one object of OutputStream class and charsetecoder and charsetname respectively.
It provides some good methods like,
  1. write(int c) :It is used to write a single character.
  2. write(String str, int off, int len) : It is used to write a portion of given string starting from offset value till the len number of characters.
  3. write(char[] cbuf, int off, int len) : It is used to write a character array starting from the offset till the len number of characters.
  4. close() : It is used to close the stream.
  5. flush() : It is used to flush the data stream.
  6. getEncoding() : It is used to retrieve the name of the character encoding being used by the stream.


Example:

package com.javaeschool.javaexamples.io;
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 osWriter = null;
OutputStream outStream = null;
File outputFile = null;
String str1 = "Hello Java.";
String str2 = "Java IO is fun.";
try{
outputFile = new File("d:\\outsWriter.txt");
outStream = new FileOutputStream(outputFile);
osWriter = new OutputStreamWriter(outStream);
System.out.println("Writing data in file..!!");
osWriter.write(str1);
osWriter.append(str2);
System.out.println("Data successfully written in file..!!");
}
catch(IOException e)
{
System.out.println("Exception caught..!!");
e.printStackTrace();
}
finally
{
try
{//closing objects
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..!!

2 comments: