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
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.
public class SWDemo
public static void main(String args) throws IOException
StringWriter swriter = new StringWriter();
PrintWriter pwriter = new PrintWriter(swriter);
pwriter.println("Cost of living");
pwriter.println("Cheaper in South India");
pwriter.write(swriter.toString()); // writing using PrintWriter object
System.out.println(swriter); // writing using StringWriter object
Three strings are written to StringWriter though PrintWriter object using println() method.
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().
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.