CharArrayWriter

In this chapter you will learn:

  1. How to use Java CharArrayWriter
  2. How to convert content in CharArrayWriter to char array

Use CharArrayWriter

CharArrayWriter is an output stream that uses an array as the destination. CharArrayWriter has two constructors, shown here:

import java.io.CharArrayWriter;
import java.io.IOException;
/*from   jav  a2 s .  c o  m*/
public class Main {
  public static void main(String args[]) throws IOException {
    CharArrayWriter outStream = new CharArrayWriter();
    outStream.write('a');
    outStream.write('b');
    outStream.write('c');
    outStream.write('d');
    outStream.write('e');
    outStream.write('f');
    outStream.write("java2s.com");
    
    System.out.println("outstream: " + outStream);
    System.out.println("size: " + outStream.size());

  }
}

The output:

Convert content in CharArrayWriter to char array

The following fill char array to a CharArrayWriter and then use toCharArray to get the char array back.

import java.io.CharArrayWriter;
import java.io.FileWriter;
import java.io.IOException;
//from   ja  va2  s . c  om
public class Main {
  public static void main(String args[]) throws IOException {
    CharArrayWriter f = new CharArrayWriter();
    String s = "This should end up in the array";
    char buf[] = new char[s.length()];
    s.getChars(0, s.length(), buf, 0);
    f.write(buf);
    System.out.println(f.toString());

    char c[] = f.toCharArray();
    for (int i = 0; i < c.length; i++) {
      System.out.print(c[i]);
    }
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use StringWriter