Java.io.Writer.write() Method



Description

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

Declaration

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

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

Parameters

  • str − String to be written.

  • off − Offset from which to start writing characters.

  • len − Number of characters to write.

Return Value

This method does not return a value.

Exception

  • IndexOutOfBoundsException − If off is negative, or len is negative, or off+len is negative or greater than the length of the given string.

  • IOException − If an I/O error occurs.

Example

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

package com.tutorialspoint;

import java.io.*;

public class WriterDemo {
   public static void main(String[] args) {
      String str = "Hello world!";

      // create a new writer
      Writer writer = new PrintWriter(System.out);

      try {
         // write a string portion
         writer.write(str, 0, 5);

         // flush the writer
         writer.flush();

         // write another string portion
         writer.write(str, 5, 6);

         // flush the stream again
         writer.flush();

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

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

Hello world
java_io_writer.htm
Advertisements