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.
import java.io.*;
public class SWDemo
{
  public static void main(String args[]) throws IOException
  {
    StringWriter swriter = new StringWriter();
    PrintWriter pwriter = new PrintWriter(swriter);
    pwriter.println("Hyderabad");     		
    pwriter.println("Cost of living");          		
    pwriter.println("Cheaper in South India");          		

    swriter.close();

    pwriter.write(swriter.toString());  // writing using PrintWriter object
    System.out.println(swriter);        // writing using StringWriter object

    pwriter.close();
 }
}

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 Comment

Your email address will not be published.