Signup/Sign In

CharArrayWriter writeTo() Method in Java

In this tutorial, we will learn about the writeTo() method from CharArrayWriter class in Java. The writeTo(Writer) method of CharArrayWriter class in Java is used to write the contents of the CharArrayWriter to another character stream.

Syntax

This is the syntax of writeTo() method this method accepts the Writer i.e. output stream that is the destination stream and does not return any value. This method throws IOException if an I/O error occurs.

public void writeTo(Writer out)    throws IOException

Example 1: WriteTo Method of CharArrayWriter

In this example, we are implementing writeTo() method firstly, we have written the data to the CharArrayWriter using write() method and then on that CharArrayWriter we are calling writeTo() method and we pass other out method as a parameter and it will copy the same data to the out object of CharArrayWriter that can be verified using toString() method.

import java.io.CharArrayWriter;
public class StudyTonight 
{
	public static void main(String[] args) throws Exception
	{ 
		CharArrayWriter charArrayWriter = new CharArrayWriter(); 
		String str = "Hello Studytonight"; 
		charArrayWriter.write(str); 
		CharArrayWriter out = new CharArrayWriter(); 
		charArrayWriter.writeTo(out); 
		System.out.println(out.toString()); 
	} 
}


Hello Studytonight

Example 2: WriteTo Method of CharArrayWriter

In this example, we are implementing writeTo() method firstly we have written the data to the CharArrayWriter using write() method and then on that CharArrayWriter we are calling writeTo() method and we pass other out method as a parameter and it will copy the same data to the out object of CharArrayWriter that can be verified using toString() method.

import java.io.CharArrayWriter;
import java.io.IOException;
class StudyTonight
{
	public static void main(String[] args) throws IOException 
	{ 
		CharArrayWriter charArrayWriter = new CharArrayWriter(); 
		charArrayWriter.write("Hello Studytonight"); 
		CharArrayWriter out = new CharArrayWriter(); 
		charArrayWriter.writeTo(out); 
		System.out.println(out.toString()); 
	} 
}


Hello Studytonight

Conclusion

In this tutorial, we learned about CharArrayWriter class in Java. The writeTo(Writer) method of CharArrayWriter class in Java is used to write the contents of the CharArrayWriter to another character stream.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.