Java.io.CharArrayWriter.toCharArray() Method



Description

The java.io.CharArrayWriter.toCharArray() method returns a array of character from this writer.

Declaration

Following is the declaration for java.io.CharArrayWriter.toCharArray() method −

public char[] toCharArray()

Parameters

NA

Return Value

The method returns array of characters.

Exception

NA

Example

The following example shows the usage of java.io.CharArrayWriter.toCharArray() method.

package com.tutorialspoint;

import java.io.CharArrayWriter;

public class CharArrayWriterDemo {
   public static void main(String[] args) {      
      CharArrayWriter chw = null;
            
      try {
         // create character array writer
         chw = new CharArrayWriter();
         
         String str = "Hello World!!";
         
         // write string to writer
         chw.write(str);
         
         // get array of character from the writer
         char[] ch = chw.toCharArray();
         
         // for each character in character array
         for (char c : ch)
         {
         
            // print character
            System.out.println(c);
         }
         
      } catch(Exception e) {
         // for any error
         e.printStackTrace();
      } finally {
         // releases all system resources from writer
         if(chw!=null)
            chw.close();
      }
   }
}

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

H
e
l
l
o
 
W
o
r
l
d
!
!
java_io_chararraywriter.htm
Advertisements