dsa

Java StringWriter

In this tutorial, we will learn about the Java StringWriter, its constructors and its methods with the help of an example.

The Java StringWriter class is a character stream that collects its output in a string buffer, which can then be used to construct a string.

Constructors of StringWriter

  • StringWriter() :This creates a new string writer using the default initial string-buffer size.
  • StringWriter(int initialSize) :This creates a new string writer using the specified initial string-buffer size.

Methods

MethodsDescription
StringWriter append(char c)Appends the specified character to this writer.
StringWriter append(CharSequence csq)Appends the specified character sequence to this writer.
StringWriter append(CharSequence csq, int start, int end)Appends a subsequence of the specified character sequence to this writer.
void close()Closing a StringWriter has no effect.
void flush()Flush the stream.
StringBuffer getBuffer()Return the string buffer itself.
String toString()Return the buffer's current value as a string.
void write(char[] cbuf, int off, int len)Write a portion of an array of characters.
void write(int c)Write a single character.
void write(String str)Write a string.
void write(String str, int off, int len)Write a portion of a string.

Examples :


import java.io.StringWriter;

public class Codemistic 
{
  	public static void main(String[] args) 
	{

    		String data = "This is the text in the string.";

    		try 
		{
      			// Create a StringWriter with default string buffer capacity
      			StringWriter output = new StringWriter();

      			// Writes data to the string buffer
      			output.write(data);

      			// Prints the string writer
      			System.out.println("Data in the StringWriter: " + output);

      			output.close();
    		}
    		catch(Exception e) 
		{
      			e.getStackTrace();
    		}
  	}
}

Output :

Data in the StringWriter: This file consists of a single line.