Home  >  Core Java

Java StringReader and StringWriter Example

By Arvind Rai, July 20, 2014
On this page we will learn java.io.StringReader and java.io.StringWriter with examples. StringReader and StringWriter works on character stream.

StringReader

StringReader takes input string and changes it into character stream.
StringReaderDemo.java
package com.cp.io;
import java.io.IOException;
import java.io.StringReader;
public class StringReaderDemo {
   public static void main(String[] args) {
        String str = "Hello World! \nThis is StringReader Program.";
        StringReader sr = new StringReader(str);
        int i=0;
        try {
	       while((i=sr.read())!=-1){
		  System.out.print((char)i);
               }
	} catch (IOException e) {
  	       e.printStackTrace();
	}
    }
} 
Find the output.
Hello World! 
This is StringReader Program.

StringWriter with BufferedReader

StringWriter can use BufferedReader to read file data as a source to be written in character array as buffer.
StringWriterDemoOne.java
package com.cp.io;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
public class StringWriterDemoOne {
	public static void main(String[] args) throws IOException {
		char[] buff = new char[1024];
		StringWriter sw = new StringWriter();
		FileInputStream fis = null;
		BufferedReader bufferReader = null;
		try {
			fis = new FileInputStream("D:/cp/file.txt");
			bufferReader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
			int n;
                        while ((n = bufferReader.read(buff)) != -1) {
                        sw.write(buff, 0, n);
                }
                System.out.println(sw.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			sw.close();
			bufferReader.close();
		}
    }
} 
Find the output.
Hello World! 
This is StringWriter Program.

StringWriter with StringBuffer

StringWriter writes character stream into a StringBuffer and finally this buffer is converted into string.
StringWriterDemoTwo.java
package com.cp.io;
import java.io.StringWriter;
public class StringWriterDemoTwo {
        public static void main(String[] args) {
		String str1 = "Hello World!";
		String str2 ="\nThis is StringReader Program.";
		StringWriter outputWriter = new StringWriter();
		outputWriter.write(str1,0,5);
		System.out.println(outputWriter.toString());
		//get  StringBuffer of outputWriter 
		StringBuffer sbuf = outputWriter.getBuffer();
		//append str2 into StringBuffer
		sbuf.append(str2);
		System.out.println(outputWriter.toString());
	}
}
 
Find the output.
Hello
Hello
This is StringReader Program.
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us