Site icon TechVidvan

Java CharArrayWriter Class

java chararraywriter

The Java.io.CharArrayWriter class implements a character buffer that can be used as a Writer. Data written to the stream automatically expands the buffer.

Explanation

The CharArrayWriter class is a subclass of the Writer abstract class. Its purpose is to write characters from a char array to a buffer that is also a char array and then from this buffer to a character stream.

Syntax

public class CharArrayWriter extends Writer

Constructor

Method

Field

Type Method Description
CharArrayWritter append(char c) Adds this writer’s specified character.
CharArrayWritter append(CharSequence csq) Appends to this writer the designated character sequence.
CharArrayWritter append(CharSequence csq, int start, int end) Attached is a portion of the designated character sequence for this writer.
void close() It shutdown the stream
void flush() Make the stream run.
void Reset() Resetting the buffer allows you to utilize it once more without wasting the previously allocated space.
int Size() Gives back the buffer’s current size.
char[] toCharArray() Gives back a duplicate of the input data.
string toString() converts the data input to a string.
Void write(char[] c, int off, int len) It enters the buffer with characters.
void write(int c) A character is written to the buffer.
void writeTo(Writer out) Writes the buffer’s contents to a different character stream.

Example

package studytonight;
import java.io.CharArrayWriter;
import java.io.FileWriter;
public class StudyTonight 
{
  public static void main(String args[]) throws Exception
  {
    CharArrayWriter writer=new CharArrayWriter();    
    writer.write("Hello Studytonight");    
    FileWriter fileWriter=new FileWriter("E:\studytonight\\output.txt");   
    writer.writeTo(fileWriter);    
    fileWriter.close();    
    System.out.println("Data is written successfully...");    
  }
}

Output
Data is written successfully…

Example

import java.io.*;
class A
{
public static void main(String... ar)
{
char[] arr1= new char[]{'j','a','v','a'};
char[] arr2= new char[]{'p','r','o','g','r',’a’,’m’};

try
{
CharArrayWriter caw= new CharArrayWriter(); 
System.out.println("Initial Size of the buffer = "+ caw.size());

for(char ch : arr1) 
{
caw.write(ch);
}

caw.write(arr2);  

System.out.println("Content of buffer = "+ caw.toString());
System.out.println("Size of the buffer = "+ caw.size());

FileWriter fw = new FileWriter("D:\\TextBook2.txt");
caw.writeTo(fw);

fw.flush();
caw.flush();
caw.close();
}		 	 
catch(IOException e)
{
System.out.println(e);
}

}
}

Output
Initial Size of the buffer = 0
Content of buffer = javaprogram
Size of the buffer = 13

Conclusion

Using the Char array writer class, we can write shared data to several files. This class creates a buffer for writing data. When data is written to the stream, this buffer expands automatically and has no set size.

Exit mobile version