Home  >  Article  >  Java  >  What is the importance of StringWriter in Java?

What is the importance of StringWriter in Java?

PHPz
PHPzforward
2023-09-10 16:57:031250browse

The

What is the importance of StringWriter in Java?

StringWriter class is a subclass of the Writer class that writes strings to the output stream. To write a string, the character stream collects the string into a string buffer and then constructs a string. StringWriter's buffer grows automatically based on data. The important methods of the StringWriter class are write(), append(), getBuffer(), flush() and close(). p>

Syntax

<strong>public class StringWriter extends Writer</strong>

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

The above is the detailed content of What is the importance of StringWriter in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete