File read write IO operation in java – StringWriter/StringReader (example)

  • We will discuss file IO operations (read and write) using StringReader and StringWriter.

File IO operation in java (StringReader and StringWriter)

  • StringWriter is used to write contents as a String
  • StringReader is used to read contents as a String.
  • We have shown content writing using StringWriter in Fig 1.
File read write StringWriter stringReader
Fig 1: Writing content to file

Code: Read write file in java – StringWriter & StringReader

package org.learn.io;

import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

public class StringReaderWriter {
	public static void main(String[] args) throws IOException {
		String contentWriten = writeUsingStringWriter();
		readUsingStringReader(contentWriten);
	}

	private static String writeUsingStringWriter() throws IOException {
		String contentWritten = "";
		String newLine = System.getProperty("line.separator");
		try (FileWriter fileWriter = new FileWriter("sampleFile.txt");
				StringWriter stringWriter = new StringWriter()) {
			stringWriter.write("Soccer");
			stringWriter.write(newLine);
			stringWriter.write("Tennis");
			stringWriter.write(newLine);
			stringWriter.write("Badminton");
			stringWriter.write(newLine);
			stringWriter.write("Hockey");
			stringWriter.write(newLine);
			contentWritten = stringWriter.toString();
			fileWriter.write(contentWritten);
			System.out.println("Writing content using StringWriter:");
			System.out.println(contentWritten);
		}
		return contentWritten;
	}

	private static void readUsingStringReader(String content) throws IOException {
		System.out.println("Reading content using StringReader:");
		try (StringReader stringReader = new StringReader(content)) {
			int ch;
			while ((ch = stringReader.read()) != -1)
				System.out.printf("%c", ch);
		}
	}
}

Output – read write file using StringWriter & StringReader

Writing content using StringWriter:
Soccer
Tennis
Badminton
Hockey

Reading content using StringReader:
Soccer
Tennis
Badminton
Hockey

Scroll to Top