In this section we will discussed about the StringWriter in Java.
java.io.StringWriter writes the String to the output stream. To write the string this character stream collects the string into a string buffer and then constructed a string. StringWriter provides the two constructors to create objects.
Constructor Detail
| StringWriter() | This is a default constructor used for creating a new StringWriter with the
default size of string-buffer. Syntax : public StringWriter() |
| StringWriter(int initialSize) | This constructor is used for creating a new StringWriter with the specified
size of string-buffer size. Syntax : public StringWriter(int initialSize) |
Method Detail
Example
An example is being given here which will demonstrate you about how to use the StringWriter in the Java program. In this example I have created a Java class named JavaStingWriterExample.java where created an object of StringWriter using which a string will be write to the stream.
Source Code
JavaStringWriterExample.java
import java.io.StringWriter;
import java.io.IOException;
public class JavaStringWriterExample
{
public static void main(String args[])
{
String str = "Java StringWriter Example";
try {
StringWriter sw = new StringWriter();
sw.write(str);
StringBuffer sb = new StringBuffer();
sb = sw.getBuffer();
System.out.println();
System.out.println("StringBuffer = "+sb);
System.out.println("String written by StringWriter = "+ sw);
System.out.println();
sw.close();
}
catch (IOException e)
{
System.out.println(e);
}
}
}
Output
When you will execute the above example you will get the output as follows :

|
Recommend the tutorial |
Ask Questions? Discuss: Java IO StringWriter
Post your Comment