Java - StringReader and StringWriter example

Posted on November 9, 2016


A StringReader class converts the ordinary string into reader, while a StringWriter class collects the character in a string buffer, which is used to construct a string. Closing  a StringReader and StringWriter has no effect.

Here is an example of StringReader class.

StringReaderExample.java

package com.boraji.tutorial.io;

import java.io.IOException;
import java.io.StringReader;

/**
 * @author imssbora
 */
public class StringReaderExample {
	public static void main(String[] args) {
		String input = "This is an example of StringReader.";
		StringReader stringReader = new StringReader(input);
		int c;
		try {
			while ((c = stringReader.read()) != -1) {
				System.out.print((char) c);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Output

This is an example of StringReader.

The following is an example of StringWriter class.

StringWriterExample.java

package com.boraji.tutorial.io;

import java.io.StringWriter;

/**
 * @author imssbora
 */
public class StringWriterExample {
	public static void main(String[] args) {
		StringWriter stringWriter = new StringWriter();
		stringWriter.write("This is an example ");
		stringWriter.write("of StringWriter.");

		// Convert writer to String
		System.out.println(stringWriter.toString());

	}
}

Output

This is an example of StringWriter.