Java.io.OutputStreamWriter.write() Method

Advertisements


Description

The java.io.OutputStreamWriter.write(String str, int off, int len) method writes a portion of a string.

Declaration

Following is the declaration for java.io.OutputStreamWriter.write() method

public void write(String str, int off, int len)

Parameters

  • str -- A String

  • off -- Offset from which to start writing characters

  • len -- Number of characters to write

Return Value

This method does not return a value.

Exception

  • IOException -- if an I/O error occurs.

Example

The following example shows the usage of java.io.OutputStreamWriter.write() method.

package com.tutorialspoint;

import java.io.*;

public class OutputStreamWriterDemo {

   public static void main(String[] args) {

      String s = "Hello world!";

      try {

         // create a new OutputStreamWriter
         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(s, 0, 5);

         // flush the stream
         writer.flush();

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


      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

Let us compile and run the above program, this will produce the following result:

Hello



Advertisements
Advertisements