Java IO Tutorial - Java OutputStreamWriter (OutputStream out, CharsetEncoder enc) Constructor








Syntax

OutputStreamWriter(OutputStream out, CharsetEncoder enc) constructor from OutputStreamWriter has the following syntax.

public OutputStreamWriter(OutputStream out,     CharsetEncoder enc)

Example

In the following code shows how to use OutputStreamWriter.OutputStreamWriter(OutputStream out, CharsetEncoder enc) constructor.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
/*from   ww w  .  j  av a 2 s .c o  m*/
public class Main {

   public static void main(String[] args) {

      String s = "from java2s.com!";

      try {

         OutputStream os = new FileOutputStream("test.txt");
         OutputStreamWriter writer = new OutputStreamWriter(os,Charset.defaultCharset().newEncoder());

         FileInputStream in = new FileInputStream("test.txt");

         writer.write(s, 0, 5);

         writer.flush();

         for (int i = 0; i < 5; i++) {
            System.out.print((char) in.read());
         }
         writer.close();
         in.close();
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

The code above generates the following result.