Programming Tutorials

CharArrayWriter sample program in Java

By: Baski in Java Tutorials on 2022-09-15  

CharArrayWriter is a class in Java that extends the Writer abstract class and provides a buffer to write characters into an internal buffer which can later be used to create a String.

Here's an example program that uses CharArrayWriter:

import java.io.CharArrayWriter;
import java.io.IOException;

public class CharArrayWriterExample {
    public static void main(String[] args) throws IOException {
        CharArrayWriter writer = new CharArrayWriter();
        String message = "Hello World!";
        writer.write(message);
        char[] buffer = writer.toCharArray();
        System.out.println(new String(buffer));
        writer.close();
    }
}

The above program creates an instance of CharArrayWriter, writes the string "Hello World!" to it, and then converts the written characters into a character array using the toCharArray() method. Finally, the character array is printed as a String.

CharArrayWriter has two constructors:

  1. CharArrayWriter(): Creates a new CharArrayWriter with a default initial size of 32 characters.
  2. CharArrayWriter(int initialSize): Creates a new CharArrayWriter with an initial buffer size of initialSize.





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)