What is the importance of a StringWriter in Java?


The StringWriter class is s subclass of Writer class and it writes the String to an output stream. To write a string, this character stream collects the string into a string buffer and then constructed a string. The buffer of StringWriter automatically grows according to data. The important methods of StringWriter class are write(), append(), getBuffer(), flush() and close().

Syntax

public class StringWriter extends Writer

Example

import java.io.*;
public class StringWriterTest {
   public static void main(String args[]) {
      String str = "Welcome to Tutorials Point";
      try {
         StringWriter sw = new StringWriter();
         sw.write(str);
         StringBuffer sb = new StringBuffer();
         sb = sw.getBuffer();
         System.out.println("StringBuffer: "+ sb);
         System.out.println("String written by StringWriter: "+ sw);
         sw.close();
      } catch (IOException ioe) {
         System.out.println(ioe);
      }
   }
}

Output

StringBuffer: Welcome to Tutorials Point
String written by StringWriter: Welcome to Tutorials Point

Updated on: 22-Nov-2023

88 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements