StringWriter Example

StringWriter Example


StringWriter Example: It is a character stream on writing-side which is capable to store data written to it. Internally it uses StringBuffer to store the data. The data written to StringWriter object can be used later in the program.

Following is the class signature

public class StringWriter extends Writer

StringWriter Example: Writing and Extracting with StringWriter
StringWriter Example: Three strings are written to the StringWriter and later extracted and printed at the DOS prompt.

StringWriter ExampleOutput screen on StringWriter Example

Three strings are written to StringWriter though PrintWriter object using println() method.

pwriter.write(swriter.toString());
System.out.println(swriter);

The data (three strings) available with StringWriter is written to DOS prompt in two ways using the objects of PrinteWriter and StringWriter. pwriter.write() statement can be replaced with pwriter.println().

swriter.close();

Even though, the StringWriter object swriter is closed before printing, the data is not lost. That is, the earlier closing of StringWriter object does not have any affect on the data it stores.

Leave a Reply

Your email address will not be published. Required fields are marked *