OutputStreamWriter : OutputStreamWriter « File « Java Tutorial






  1. An OutputStreamWriter is a bridge from character streams to byte streams.
  2. Characters written to an OutputStreamWriter are encoded into bytes using a specified character set.

The OutputStreamWriter class has four constructors:

public OutputStreamWriter (OutputStream out)
public OutputStreamWriter (OutputStream out, java.nio.charset. Charset cs)
public OutputStreamWriter (OutputStream out, java.nio.charset. CharsetEncoder enc)
public OutputStreamWriter (OutputStream out, String encoding)
  1. The first constructor creates an instance that uses the default encoding.
  2. The others allow you to pass the encoding.
  3. The OutputStreamWriter class adds the getEncoding() to return the encoding in string.
  4. import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class MainClass {
  public static void main(String[] args) {
    try {
      char[] chars = new char[2];
      chars[0] = '\u4F60';
      chars[1] = '\u597D';
      String encoding = "GB18030";
      File textFile = new File("C:\\temp\\myFile.txt");
      OutputStreamWriter writer = new OutputStreamWriter(

      new FileOutputStream(textFile), encoding);
      writer.write(chars);
      writer.close();
    } catch (IOException e) {
      System.out.println(e.toString());
    }
  }
}








11.16.OutputStreamWriter
11.16.1.OutputStreamWriter
11.16.2.Writing UTF-8 Encoded Data
11.16.3.Writing ISO Latin-1 Encoded Data