Java IO Tutorial - Java OutputStreamWriter .write (char[] cbuf, int off, int len)








Syntax

OutputStreamWriter.write(char[] cbuf, int off, int len) has the following syntax.

public void write(char[] cbuf,  int off,  int len)  throws IOException

Example

In the following code shows how to use OutputStreamWriter.write(char[] cbuf, int off, int len) method.

/*w w  w. j ava 2  s . c o m*/

import java.io.*;

public class Main {

   public static void main(String[] args) {

      char[] arr = {'H', 'e', 'l', 'l', 'o'};

      try {

         OutputStream os = new FileOutputStream("test.txt");
         OutputStreamWriter writer = new OutputStreamWriter(os);

         // create a new FileInputStream to read what we write
         FileInputStream in = new FileInputStream("test.txt");

         // write something in the file
         writer.write(arr, 0, 3);

         // flush the stream
         writer.flush();

         // read what we write
         for (int i = 0; i < 3; i++) {
            System.out.print((char) in.read());
         }

         writer.close();
         in.close();
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

The code above generates the following result.