Stringwriter

The StringWriter class in Java functions as a character stream that gathers output from a string buffer, enabling the construction of a string. This class is a subclass of the Writer class.

In the StringWriter class, there is no utilization of system resources such as network sockets and files. As a result, there is no requirement to explicitly close the StringWriter.

Java StringWriter class declaration

Let's examine the declaration of the Java.io.StringWriter class:

Example

public class StringWriter extends Writer

Methods of StringWriter class

Method Description
void write(int c) It is used to write the single character.
void write(String str) It is used to write the string.
void write(String str, int off, int len) It is used to write the portion of a string.
void write(char[] cbuf, int off, int len) It is used to write the portion of anarrayof characters.
String toString() It is used to return the buffer current value as a string.
StringBuffer getBuffer() It is used t return the string buffer.
StringWriter append(char c) It is used to append the specified character to the writer.
StringWriter append(CharSequence csq) It is used to append the specified character sequence to the writer.
StringWriter append(CharSequence csq, int start, int end) It is used to append the subsequence of specified character sequence to the writer.
void flush() It is used to flush the stream.
void close() It is used to close the stream.

Java StringWriter Example

Let's explore a basic example demonstrating the utilization of StringWriter in conjunction with BufferedReader for reading data from a file via stream.

Example

import java.io.*;
public class StringWriterExample {
	public static void main(String[] args) throws IOException {
		char[] ary = new char[512];
		StringWriter writer = new StringWriter();
		FileInputStream input = null;
		BufferedReader buffer = null;
		input = new FileInputStream("D://testout.txt");
		buffer = new BufferedReader(new InputStreamReader(input, "UTF-8"));
		int x;
		while ((x = buffer.read(ary)) != -1) {
                   writer.write(ary, 0, x);
		}
		System.out.println(writer.toString());		
		writer.close();
		buffer.close();
    }
}

testout.txt:

Example

C# Tutorial provides tutorial in Java, Spring, Hibernate, Android, PHP etc.

Output:

Output

C# Tutorial provides tutorial in Java, Spring, Hibernate, Android, PHP etc.

Input Required

This code uses input(). Please provide values below: