Java StringWriter Class

The StringWriter class is a stream of characters that contains the output of a buffer string, which can be used to create a string. There’s no impact when you close the StringWriter. After the stream is shut down, methods can be called from this class without throwing an IOException. Constructors in the Java StringWriter class:

Below is the constructor used for Java’s StringWriter class:

StringWriter(): Creates a new string writer using the initial or default buffer size.

StringWriter(int size): Creates a new StringWriter using the specified.

Create a StringWriter

We must first ensure that we import the java.io.StringWriter package before creating a StringWriter. This is where we can get a string writer once the package has been imported.

 // Creates a StringWriter
 The output of the StringWriter is new StringWriter; 
Here we're creating a string writer that has default buffer capacity. However, we can also define a buffer size for the string. 
// Initializes a string writer with specified buffer capacity 
StringWriter output= a new StringWriter(ints' size; 
The size specifies the string buffer's capacity here.

write() Method:

Write() writes a single character to the string writer. write(char[] array) – writes the characters from the specified array to the writer write(String data) – writes the specified string to the writer

Program:

import java.io.StringWriter;
public class TechVidvan {
  public static void main(String[] args) {
    String data = "This is the text in the string.";
Try {
      StringWriter output = new StringWriter();
           output.write(data);
      System.out.println("Data in StringWriter: " + output)
      output.close();
    }

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

Output:
Data in the StringWriter: This is the text in the string.

Use a StringBuffer to access data:

The data that is present in the string buffer shall be returned by getBuffer(). When toString() is called, it returns the data in the buffer as a string.

Example:

import java.io.StringWriter;
public class TechVidvan {
  public static void main(String[] args) {
 String data = "This is the original data";
    Try {
       StringWriter output = new StringWriter();
           output.write(data);
         StringBuffer stringBuffer = output.getBuffer();
      System.out.println("StringBuffer: " + stringBuffer);
           String string = output.toString();
      System.out.println("String: " + string);
      output.close();
    }
     catch(Exception e) {
      e.getStackTrace();
    }
  }
}

Output:
StringBuffer: This is the original data
String: This is the original data

Close() Method:

Close() will be used for closing the string writer. However, the StringWriter class is unaffected by a Close() method. Even after calling the close() function, we can call methods of this class.

Example:

packet TechVidvan;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
public class StudyTonight
{
public static void main(String args[])
{
Try
{
char[] arr = new char[512];
StringWriter writer = new StringWriter();
FileInputStream input = new FileInputStream("E:\\tech vidvan\\output.txt");
BufferedReader buffer = new BufferedReader(new InputStreamReader(input, "UTF-8"));
int c;
while ((c = buffer.read(arr)) != -1) {
writer.write(arr, 0, c);
}
System.out.println(writer.toString());
writer.close();
buffer.close();
}
catch (exception e)
{
System.out.println("Error: "+e.toString());
}
}
}

Output:
Hello TechVidvan

A simple use case

 import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
 
public class StringWriterExample {
    public static void main(String[] args) throws IOException {
        String str1 = stringWriter("F:\\nikos7\\Desktop\\s.txt");
        System.out.println(str1);
    }
    public static String stringWriter(String fileName) throws IOException {
        char[] buff = new Char[1024];
        Writer stringWriter = new StringWriter();
        FileInputStream fStream = null;
        Reader bReader = null;
        Try {
           fStream = new FileInputStream(fileName);
            bReader = new BufferedReader(new InputStreamReader(fStream, "UTF-8"));
            int n;
            while ((n = bReader.read(buff)) != -1) {
                stringWriter.write(buff, 0, n);
            }
        } Finally {
            bReader.close();
            stringWriter.close();
            fStream.close();
        }
        return stringWriter.toString();
    }
}

Advantage

  • The use of Sfring methods to work with their content is easy.
  • The use of an “+” operator allows for a higher performance relative to classical string concatenation.
  • New string objects have been created for each concatenation, which leads to unallocated memory and object creation when consolidating multiple strings using the Windows+” operator.

Conclusion

Java’s StringWriter class. The Java StringWriter class is a character stream that takes output from the string buffer, for example, when you want to construct a string.